Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Advanced Custom Fields ACF dynamically set default value #wordpress
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;

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.


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.


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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.