Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Advanced Custom Fields ACF dynamically set default value #wordpress
<?php
add_filter('acf/load_field/name=field_name', function($field) {
global $post;
// variant 1 (use get_post_meta instead of get_field to avoid conflicts)
if( get_post_meta($post->ID, 'field_name', true) == '' ) {
$field['value'] = 'FOO';
}
// variant 2
$field['default_value'] = 'FOO';
return $field;
});
@braddalton

This comment has been minimized.

Copy link

@braddalton braddalton commented Jun 7, 2019

Thanks for this. I might be wrong but variant 1 works and variant 2 doesn't.

@vielhuber

This comment has been minimized.

Copy link
Owner Author

@vielhuber vielhuber commented Jun 7, 2019

Hello Brad, thanks for your feedback.
I just tried both versions successfully with WP 5.2.1 and ACF 5.8.1.

@pawelskaba

This comment has been minimized.

Copy link

@pawelskaba pawelskaba commented Jan 28, 2020

Hi thanks for the snippet. Got a question - I've created sth like that but seems not to work:

function my_acf_load_field( $field ) {
    global $post;
    if( get_post_meta($post->ID, 'month_year', true) == '' ) {
        $current_date = get_sub_field('data');
        $trimmed = substr($current_date, -7);
        $field['value'] = $trimmed;
    }
    $field['disabled'] = 1;
    return $field;
}
add_filter('acf/load_field/name=month_year', 'my_acf_load_field');
@dima8nep

This comment has been minimized.

Copy link

@dima8nep dima8nep commented Mar 13, 2021

I found how to set shortcote in default value.
Add in functions.php
If your shortcode have '' in [] and no "";
Use the plugin "Shortcoder" https://wordpress.org/plugins/shortcoder

add_filter('acf/load_field/name=latitude', function($field) {
$field['default_value'] = '' . do_shortcode('[sc name="latitude"]') . '';
return $field;
});
add_filter('acf/load_field/name=longitude', function($field) {
$field['default_value'] = '' . do_shortcode('[sc name="longitude"]') . '';
return $field;
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment