Search code examples
phpwordpressadvanced-custom-fields

I am trying to get the ACF field default value


I have added a ACF field for torque and set its default value. But the default value is not showing in my existing products.

I want to get the ACF field (torque) default value also in my existing products.

When i add a new product the ACF field (torque) default value is showing.


Solution

  • ACF field values are saved as post_meta at the exact moment the post gets saved. So they won't be there for posts that have been saved before the ACF field existed (or had a default value).

    You have two options now. Either check for the field values for being empty before you output them (and set a default value in that case) by:

    $field_value = get_field('field_name');
    if(empty($field_value)) $field_value = 'default_value';
    
    //Do not use the_field() to output the value but
    echo $field_value;
    

    or write a script to run once and add the default value to all of the older posts. Something like:

    $args = array(
        'post_type' => 'post', //Change if other post_type
        'posts_per_page' => -1 
    );
    
    $products = new WP_Query( $args );
    
    
    while($products->have_posts()) {
        $products->the_post();
    
        if(empty(get_field('field_name'))) {
            update_field('field_name', 'default_value');
        }
    }