Skip Navigation

[Resolved] Update posts after setting default value to custom field

This support ticket is created 5 years, 7 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 2 replies, has 2 voices.

Last updated by ELAN42 5 years, 7 months ago.

Assisted by: Christian Cox.

Author
Posts
#1276573

Hello,
Suppose I have a numeric custom field and sometime later I decide I want it to have a default value.

What I noticed is that the corresponding row in the wp_postmeta table is not created until that post is actually saved again from its back-end.

Since I need those DB rows for later purposes, how could I mass update/save posts?

(WP-CLI is fine, in case)

#1276615

Hi, there's nothing built-in to Toolset that will automatically set the default values without editing the posts in wp-admin. There are some 3rd party plugins out there that claim to be able to update custom field values in bulk edit mode, but I can't verify their effectiveness. Apart from that, you would have to write a custom script that selects all posts of that particular post type where the custom field value does not exist. Then set the default value for those posts. I don't have that specific custom script code available for you, but a quick search led to some other examples. To find posts:
https://wordpress.stackexchange.com/questions/80303/query-all-posts-where-a-meta-key-does-not-exist

To set a custom field value:
https://codex.wordpress.org/Function_Reference/update_post_meta

Set a custom field value when looping over posts:

// ...set up your query args in $args before this line
$ps = get_posts( $args );
foreach( $ps as $p ) {
  update_post_meta( $p->ID, 'wpcf-fieldslug', 'default value' );
}

Remember that Types fields have a "wpcf-" prefix in the database, so if you're using WP Query or SQL directly you should always include that prefix.

#1279445

Thanks, we'll keep that in mind.