首页 > 解决方案 > 函数 Hook add_post_meta ACF Post 对象

问题描述

我在functions.php中有一个函数:

function create_whiteboard( $form_id, $post_id, $form_settings ) {
$current_user = wp_get_current_user();
$post_id = wp_insert_post(array (
'post_type' => 'whiteboard',
'post_title' => 'Whiteboard for ' . $current_user->user_firstname . ' ' . $current_user->user_lastname,
'post_status' => 'publish',
));
add_post_meta($post_id, 'project_select', $post_id, true);
}
add_action('create_whiteboard_hook', 'create_whiteboard', 10, 3 );

这样做的原因是它在白板帖子类型中创建了一个帖子 - 但它不会更新我的帖子对象字段 (project_select)。如果我指定一个 ID:

add_post_meta($post_id, 'project_select', '1', true);

然后它确实有效 - 我的问题是如何将刚刚创建的帖子的 ID 传递给这个?

标签: phpwordpressadvanced-custom-fields

解决方案


被从的$post_id返回值赋值覆盖wp_insert_post

照原样,创建的白板帖子是用元数据装饰的,而不是预期的帖子。

您可以通过为引用从调用返回值的变量使用不同的名称来解决此问题wp_insert_part

function create_whiteboard( $form_id, $post_id, $form_settings ) {
  $current_user = wp_get_current_user();
  $whiteboard_post_id = wp_insert_post(array (
    'post_type' => 'whiteboard',
    'post_title' => "Whiteboard for {$current_user->user_firstname} {$current_user->user_lastname",
    'post_status' => 'publish',
  ));

  add_post_meta($post_id, 'project_select', $whiteboard_post_id, true);
}

推荐阅读