最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Only show certain post types in recent posts widget

programmeradmin0浏览0评论

I have a custom post type which has been made to show in archives using the code below in my theme's functions.php :

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
    if ( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
        $post_type = get_query_var('post_type');
        $post_types = get_post_types();
        if($post_type)
            $post_type = $post_type;
        else
            $post_type = $post_types;
        $query->set('post_type',$post_type);
        return $query;
    }
}

The problem is that pre_get_posts basically altered the query for recent posts widget, causing it to display all post types in this case. However, since I am using WooCommerce, the shop products are also shown which I would like to avoid.

So, is there any way I can make the recent posts show only standard WordPress posts and a custom post type, while keeping the custom post type visible in archives?

I have a custom post type which has been made to show in archives using the code below in my theme's functions.php :

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
    if ( is_archive() && empty( $query->query_vars['suppress_filters'] ) ) {
        $post_type = get_query_var('post_type');
        $post_types = get_post_types();
        if($post_type)
            $post_type = $post_type;
        else
            $post_type = $post_types;
        $query->set('post_type',$post_type);
        return $query;
    }
}

The problem is that pre_get_posts basically altered the query for recent posts widget, causing it to display all post types in this case. However, since I am using WooCommerce, the shop products are also shown which I would like to avoid.

So, is there any way I can make the recent posts show only standard WordPress posts and a custom post type, while keeping the custom post type visible in archives?

Share Improve this question edited Dec 6, 2014 at 9:21 Pieter Goosen 55.4k23 gold badges115 silver badges210 bronze badges asked Dec 6, 2014 at 9:17 BillyBilly 2492 silver badges14 bronze badges 2
  • possible duplicate of Number of posts in page - set per category and exclude sidebar – Pieter Goosen Commented Dec 6, 2014 at 9:29
  • Thank you @PieterGoosen! That's exactly what I wanted to achieve but I wasn't aware of is_main_query. – Billy Commented Dec 6, 2014 at 13:34
Add a comment  | 

1 Answer 1

Reset to default 1

Use the widget_posts_args filter

add_filter('widget_posts_args', 'wpsites_modify_recent_posts_widget');
function wpsites_modify_recent_posts_widget($params) {
$params['post_type'] = array('post', '$post_type');
return $params;
} 

Source

发布评论

评论列表(0)

  1. 暂无评论