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

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.

Leave a Comment