Home › Forums › Backend Issues (wp-admin) › Adding new field to existing posts
I recently added a new custom field with a default value to WooCommerce product type. I want this field to be saved to all products without having to go to each product and hitting save. Is it possible to automate or mass save all products so the custom field saves for each product?
Check this out:
$args = array(
'post_type' => 'product', /* product post type */
'posts_per_page' => -1 /* all products */
);
$products = new WP_Query( $args );
// check if products exists
if( $products->have_posts() ) {
// loop products
while( $products->have_posts() ): $products->the_post();
// check if field exists
if( !get_field( 'field_slug' ) ) {
update_field( 'field_slug' ); /* update field */
}
endwhile;
// reset query to default query
wp_reset_postdata();
}
While Kevin’s suggestion will get done what you want to do, I find it a much better alternative to check fields in the template. For example, I would never add something like
<span><?php the_field('my-field'); ?></span>
without checking to see if it has a value first
<?php
if (get_field('my-field')) {
?><span><?php the_field('my-field'); ?></span><?php
}
?>
Since I’m already checking the value I would alter my check to:
<?php
$value = get_field('my-field');
if (!$value) {
$value = 'my default value';
}
?><span><?php echo $value; ?></span>
This makes in unnecessary for me to retroactively add the field to the database.
@pixelbart Unfortunately this isn’t working any more. update_field requires more arguments.
https://www.advancedcustomfields.com/resources/update_field/
Is there another solution to bulk save posts so the new custom field with a default value?
$new_value = 'my new value';
if ( $new_value !== get_field( 'field_slug' ) ) {
update_field( 'field_slug', $new_value ); /* update field */
}
The topic ‘Adding new field to existing posts’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.