I have 2 post types in my theme, the default post type and a custom article post type. I publish my posts under different categories, and my articles ONLY under a single category named blog, which doesn’t contain any default post type.

I don’t want my article to be shown next to post in archive and category pages. Right now i’m using this in my archive.php:

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); 
        the_title();
    }
}

And trying to modify the main query by the following code in my functions.php file:

add_action( 'pre_get_posts', 'archive_filtering' );
function archive_filtering($query){
    if (!is_post_type_archive('article') && $query->is_main_query() && $query->is_archive()){
        if ( $query->query[ 'post_type' ] === NULL && $query->found_posts() == '0' ) {
            $query->set('post_type', 'article' );
        }
    }
}

But this doesn’t work. It now works for blog category, but the normal posts are not shown in other categories at all.

How can i check and see if the query has no default post type, BUT has some custom post type to filter it?
Thanks.

PS : I can’t use if (is_category('blog')) since i don’t know what category my customers will use to publish their articles under.

Read more here: How to modify main query if there is a custom post type in it?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: