如何使用现有 API 通过 wp_remote_post 或其他方法更新帖子元或 ACF 字段?
function publish_content($post_id, $post, $update)
{
// If this is just a revision, don't send the email.
if (wp_is_post_revision($post_id)) {
return;
}
$full_content = get_field('full_content', $post_id);
$login = 'username';
$password = 'password';
$response = wp_remote_post(
'https://example.com/wp-json/wp/v2/posts/12',
array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode("$login:$password")
)
)
);
//I need Update ACF Field Value in example.com site
}
add_action('save_post', 'publish_content', 11, 3);
我不想在目标网站上开发新的 API,我想使用现有的 (wp/v2/posts/{id}) WordPress API。
$api_response = wp_remote_post( 'yourwebiste.com/wp-
json/wp/v2/posts/893',
array(
'headers' => array('Authorization' => 'Basic ' . base64_encode(
"$login:$password" )),
'body' => array(
'acffieldname' => '2150',
),
));
“d_amount”上方是acf字段,现在你只需要在function.php或插件文件中粘贴以下代码:
function register_related_posts_api_field()
{
register_rest_field('posttype', 'd_amount',
array(
'get_callback' => function($post){ return get_field('d_amount',
$post['id']);}
'update_callback' => function ($value, $object, $fieldName)
{
return update_field("d_amount",$value,$object->ID);},
'schema' => null,
)
);
}
add_action('rest_api_init', 'register_related_posts_api_field');
注意:'d_amount' 上面是 acf 字段名 上面的代码将为您创建一个 rest api 字段,该字段将在同一个 wp api 上调用和更新