Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active March 3, 2023 02:34
Show Gist options
  • Save vielhuber/1124e0309bb4d655bfc08e1d38ad5bde to your computer and use it in GitHub Desktop.
Save vielhuber/1124e0309bb4d655bfc08e1d38ad5bde to your computer and use it in GitHub Desktop.
Advanced Custom Fields ACF dynamically set default value #wordpress
<?php
add_filter('acf/load_field/name=field_name', function($field) {
// variant 1
$field['default_value'] = 'FOO';
// variant 2 (does not work anymore)
// use get_post_meta instead of get_field to avoid conflicts
global $post;
if( get_post_meta($post->ID, 'field_name', true) == '' ) {
$field['value'] = 'FOO';
}
// if field should be disabled
$field['disabled'] = 1;
return $field;
});
@kaanaytemir
Copy link

kaanaytemir commented Aug 26, 2022

For the ones who are looking for a solution:

<?php
add_filter('acf/load_field/name=field_name', function($field) {
     
    // variant 1
    $field['default_value'] = 'FOO';

    // variant 2 (does work with most recent ACF plugin)

    if( get_post_meta($post->ID, 'field_name', true) == '' ) {
        $field['value'] = 'FOO';
    }
    
    return $field; 
    
});

This code works when you remove global $post;.

Most probably you are already setting this, so it will give a Cannot Modify Header Information – Headers Already Sent error. That error will not show the text you would like to fetch.

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