Show Custom Post Type by Author

I would like to set up a function in my functions.php file in a theme so that when a custom-post-type is being viewed, if the user clicks the author name in the post, it only shows CPTs by that author, but on the main blog if they click the author name it will only show the blog posts of that author. I already have the author names showing in my custom post and normal post meta and I have an archive-cpt.php file which is working as it should.

The pseudo code would be :

if (post == custom post type) {

    // only show custom post types by author when author name is clicked

} else {

    // only show blog posts by author when author name is clicked

}

I seem to have been going round in circles for 2 days and I'm getting nowhere.

Also I'd be happy to take a solution if it means using the author.php page as well. I'm thinking it would just be easier in the functions.php file.

Any help would be amazing.

Topic author archives custom-post-types Wordpress

Category Web


You will need to filter 'author_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.

add_filter( 'author_link', 'myprefix_author_link', 10, 3 );
function myprefix_author_link( $link, $author_id, $author_nicename ) {
    if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {
        $link = add_query_arg( 'post_type', 'myCPT', $link );
    }
    return $link;
}

The default (your else clause) will show only posts anyway, so no new code is needed for that.


SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]

About

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