Last active
March 3, 2023 02:34
-
-
Save vielhuber/1124e0309bb4d655bfc08e1d38ad5bde to your computer and use it in GitHub Desktop.
Advanced Custom Fields ACF dynamically set default value #wordpress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
}); |
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
Got it to work, actually your update to the post helped me a lot. But the Disabled, didnt work. Thank you so much, you relieved me 3 days of full stress... Now the problem is that it takes time to load the pages.