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;
});
@ful1to
Copy link

ful1to commented Apr 30, 2021

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; 
});

@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