admin管理员组

文章数量:1298182

I'm trying to get my Custom Post Type to show up in the main archive using pre_get_posts, but it just won't work.

However, in the search results the entries are displayed, and they are also displayed within an assigned category.

The code I use:

function include_custom_post_type_archives($query) {

    if ((is_category() || is_tag()) && $query->is_archive() && empty($query->query_vars['suppress_filters'])) {

        $query->set('post_type', array('post', 'landingpages'));

    }
    return $query;
}
add_filter('pre_get_posts', 'include_custom_post_type_archives');

I'm trying to get my Custom Post Type to show up in the main archive using pre_get_posts, but it just won't work.

However, in the search results the entries are displayed, and they are also displayed within an assigned category.

The code I use:

function include_custom_post_type_archives($query) {

    if ((is_category() || is_tag()) && $query->is_archive() && empty($query->query_vars['suppress_filters'])) {

        $query->set('post_type', array('post', 'landingpages'));

    }
    return $query;
}
add_filter('pre_get_posts', 'include_custom_post_type_archives');
Share Improve this question edited Sep 4, 2021 at 18:48 anyway asked Sep 3, 2021 at 4:37 anywayanyway 134 bronze badges 1
  • Be aware that is_main_query() does not refer to the "main archive". It refers to the primary query for content for every view. On a single page the main query is the query for that page, on a date archive it's the query for posts from that date, and on taxonomy archives it's the query for posts in that taxonomy term. If you want to apply the filter to the blog query then you need to use $query->is_home(). – Jacob Peattie Commented Sep 3, 2021 at 9:55
Add a comment  | 

1 Answer 1

Reset to default 1

Okay, this is what works for me, thanks to the friendly hint of Jacob Peattie:

function include_custom_post_type_archives($query)
{
    if (is_home() && empty($query->query_vars['suppress_filters'])) {
        $query->set('post_type', array(
            'post', 'landingpages',
        ));
        return $query;
    }
}
add_filter('pre_get_posts', 'include_custom_post_type_archives');

本文标签: custom post typesCPT is simply not displayed in the main archive with quotpregetpostsquot