I have a custom post that contains a field named ‘user_id’ of type User and a repeater field named details.
I want to create a new post with the user that is currently logged in.
The problem is that I can create the new post with no errors but the user_id field is not populated.
Here is the code:
$current_user = wp_get_current_user();
$new_post = array(
‘post_title’ => ‘Planner for ‘.$current_user->display_name,
‘post_type’ => ‘planner’,
‘user_id’ => wp_get_current_user(),
‘post_author’ => $_SESSION[‘USER_ID’],
‘post_status’ => ‘publish’
);
$post_id = wp_insert_post( $new_post, $wp_error );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
Anyone have any ideas why the user_id field is not filled in. I have it set as required on the custom post type but the post is created even when it is not filled in.
Thank you!
wp_current_user()
returns a User object. To get the ID you would need to access it like:
$current_user->ID
So your code would be updated to:
$current_user = wp_get_current_user();
$new_post = array(
'post_title' => 'Planner for '.$current_user->display_name,
'post_type' => 'planner',
'user_id' => $current_user->ID,
'post_author' => $_SESSION['USER_ID'],
'post_status' => 'publish'
);
$post_id = wp_insert_post( $new_post, $wp_error );
if (is_wp_error($post_id)) {
$errors = $post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
I know the name is misleading but the field is of type User so I don’t understand why wp_current_user() doesn’t work.
I attached a picture of what my custom fields look like.
Thanks
You can’t insert or update meta values when inserting or updating a post, which I assume you are trying to do. You need to use update_field() to update the custom field after you have inserted the post. https://www.advancedcustomfields.com/resources/update_field/. And you will need to use the field key when updating the field in this case. See the documentation for more information.
Ok. Thanks. I thought I tried that but I will try again and see what happens.
Thanks again