Home Forums Backend Issues (wp-admin) Adding new field to existing posts


Adding new field to existing posts

    • amjad

    • April 17, 2018 at 10:14 am

    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 */
      // reset query to default query
  • 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

      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:

      $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.

  • That’s why you’re a Lead Web Developer! 🙂

    • amjad

    • April 21, 2018 at 2:37 am

    Thanks folks. Appreciate it!

    • amjad

    • February 14, 2020 at 11:43 am

    @pixelbart Unfortunately this isn’t working any more. update_field requires more arguments.

    Is there another solution to bulk save posts so the new custom field with a default value?

  • @amjad

    $new_value = 'my new value';
    if ( $new_value !== get_field( 'field_slug' ) ) {
        update_field( 'field_slug', $new_value ); /* update field */
Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.

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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.