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; | |
}); |
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.
<?php
add_filter('acf/load_value/name=precio_lifehuni', function($field) {
global $post;
$var_id = get_post_meta($post->ID, 'id_producto_lifehuni', true);
$ch_lf = curl_init('https://app.milifehuni.com/public/ws/get_price/'.$var_id);
curl_setopt($ch_lf, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_lf, CURLOPT_HEADER, 0);
$lf_data = curl_exec($ch_lf);
curl_close($ch_lf);
return $lf_data;
get_post_meta($post->ID, 'precio_lifehuni', true);
$field['default_value'] = $lf_data;
$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
Yeah, doing some testing here aswell it looks like the curl its not running when its called or its data is not being captured. Have no idea how, why or what to do.