Search code examples
phpwordpressadvanced-custom-fieldscustom-wordpress-pageswordpress-admin

Wordpress how to assign text to the a post custom field based on the post id


I have this code which is meant to print text to a custom field.

The code works when I manually enter the post id like this example 4221.

However, I need to fetch the post id using $wp_query->post->ID;

//works
$post_id = '4221';
$field_key = "field_607aa2cb60022";
$value ="some tring for testing";
update_field( $field_key, $value, $post_id );

//Dynamically, won't work
$post_id = "'$wp_query->post->ID;'";
$field_key = "field_607aa2cb60022";

$value = "some tring for testing";
update_field( $field_key, $value, $post_id );

I wrapped $wp_query->post->ID; inside single and double quotes so as to return the number in single quotes '4221'. I can't get it to work without manually specifying the post id which is something I want to avoid and just use the current post id.

Not sure how to go about it.

Additional Images Field type

Where I need to display the text


Solution

  • Try to hook it to wp_head action hook.

    add_action('wp_head', 'populating_your_custom_field');
    
    function populating_your_custom_field(){
    
      $your_custom_field_value = get_field("field_607aa2cb60022");
    
      if (empty($your_custom_field_value)) {
    
        $your_custom_field_value = "My custom field text to test this";
    
        update_field("field_607aa2cb60022", $your_custom_field_value); 
        // Notice that you don't have to pass the id here because the default is the current post id
        // AND we used wp_head action hook. On every page load of your post, this will run
        
      }
    }
    
    

    This code would go to your functions.php.