Search code examples
wordpresswordpress-themingpostswordpress-rest-apiauthor

Custom Post Type & Author not associating, user post count is 0, api doesn't return author in post objects


When Users create custom post types, the author field does not seem to be passed back to WP posts functions.

As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post_type = 'job'.

This all LOOKS good in the database - the user, and post are inserted. The post_author is indeed the same as the ID of the user who created it.

But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.

I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp_update_post();

Here's the code to create the user, and then the post:

// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );

//login
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie  ( $user_id );

// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );

//Ready data for linked post type creation 
$new_post = array(
    'post_content' => $email_address,
    'post_status' => 'publish',
    'post_date' => date('Y-m-d H:i:s'),
    'post_author' => $user_id,
    'post_title' => $post_name,
    'post_name' => $post_name,
    'post_type' => $user_type
);

//Create the post 
$account_link_post_id = wp_insert_post($new_post);

Solution

  • There was an associated post to this one that shed light on this answer. When registering the post type, I was not setting enough fields in the 'supports' array of the register_post_type. Adding author, whatdayaknow, gives me the datapoint I'm looking for.

    register_post_type(self::POST_TYPE,
      array(
       'labels' => $labels,
       'public' => true,
       'has_archive' => true,
        'description' => __(""),
           'supports' => array(
              'title', 'author'
        ),
      )
    )
    

    NOTE: Post count in the User Accounts page is still 0 - but, the API is returning the data I want/need.