简体   繁体   中英

Functions Hook add_post_meta ACF Post Object

I have a function in 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 );

This works in that it creates a post in whiteboard post type - but it doesn't update my post object field (project_select). If I specify an ID:

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

Then it does work - my question is how do I pass the ID of the post just created into this?

The $post_id is overwritten by the assignment of the return value from wp_insert_post .

As is, the whiteboard post created is the one being decorated with the metadata and not the intended post.

You can fix this by using a different name for the variable referencing the return value from call to 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM