Wordpress 如何根据 post id 将文本分配给 post 自定义字段

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

我有这段代码,用于将文本打印到自定义字段。

当我像这个例子 4221.

手动输入 post id 时代码有效

但是,我需要使用 $wp_query->post->ID;

获取 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 );

我将 $wp_query->post->ID; 包裹在单引号和双引号内,以便 return 单引号 '4221' 中的数字。如果不手动指定 post id,我无法让它工作,这是我想避免的,只使用当前的 post id。

不知道该怎么做。

其他图片

尝试将其挂接到 wp_head 操作挂钩。

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

此代码将转到您的 functions.php