How to add author role as a custom field to custom post type in wordpress?

I want to add a custom field in the wordpress custom post type, such that this field dynamically fetches the value of the author role.

Purpose -

I want to add this custom field so that I can filter custom post types based on the user role of the author of the posts, that is editor, subscriber, etc.

What have I tried?

Well, I looked up the solution on Internet but couldn't find one and I am not that great in PHP so couldn't give it a shot myself.

Kindly suggest a solution.

Thanks a lot, in advance.

Topic user-roles Wordpress

Category Web


You can hook into save_post_{$post->post_type} which fires after the post has been saved in database.

function wpse405375_save_author_role_as_meta( $post_ID, $post, $update ) {
    
    //Get the User object from author id.
    $author = get_user_by( 'ID', $post->post_author );
    
    //Get author roles
    $roles = $author->roles;
    
    //Store the role/roles in post meta
    
    /* This one will store all the roles as serialized array. */
    update_post_meta( $post_ID, '_author_roles', $roles );
    
    /* If you want just the first role as string (in case the user is associated with multiple roles)
     * Or, in your case, use it for a simple meta_query
    */
    update_post_meta( $post_ID, '_author_role', $roles[0] );
    
}
add_action( 'save_post_MYCPT', 'wpse405375_save_author_role_as_meta', 10, 3 );

Replace MYCPT with your CPT.

EDIT : 07-05-2022

function wpse405375_change_user_posts_meta(  $user_id, $role, $old_roles ) {
    
    //Get User's posts first
    $posts = get_posts(array(
        'post_type' => 'MYCPT', //Change it to your CPT
        'posts_per_page' => -1,
        'author' => $user_id,
    ));
    
    //Loop through the posts and update meta
    if ( $posts && !empty($posts) ) {
        foreach( $posts as $post ) {
            update_post_meta( $post->ID, '_author_role', $role );
        }
    }
}
add_action( 'set_user_role', 'wpse405375_change_user_posts_meta', 10, 3);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.