[英]Exclude category Wordpress (WP_Query not working)
谁能解释为什么这个查询不起作用? 我想排除标有主页的帖子。 它仍然显示类别名称为“主页”的帖子......
<?php
$query = new WP_Query( 'category_name=-homepage');
?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
get_template_part( 'content', 'news' );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
如文档中所给出的,如果要排除类别,则必须使用其ID而不是笨拙(请在此处检查)。
您可以尝试:
$query = new WP_Query( array( 'category__not_in' => array( 11 ) ) );
您的代码中有2个问题。
您正在使用子弹而不是ID来排除类别,并且您的自定义查询没有正确使用循环。
<?php
$query = new WP_Query( array(
'cat' => -5, // replace with correct category ID.
) );
if ( $query->have_posts() ) :
// make sure we use have_posts and the_post method of our custom query.
while ( $query->have_posts() ) : $query->the_post();
get_template_part( 'content', 'news' );
endwhile;
else:
get_template_part( 'content', 'none' );
endif;
超出最初问题的范围,您不能在自定义循环内使用the_posts_navigation()
。 它作用于全局$wp_query
。 我怀疑您可能想看一下pre_get_posts
过滤器。
进一步阅读:
http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
要在搜索中排除类别,请使用:
<?php
function search_filter($query)
{
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search)
{
$taxquery = array(
array(
'taxonomy' => 'category',
'field' => 'term_taxonomy_id',
'terms' => 244,
'operator' => 'NOT IN',
)
);
$query->set( 'tax_query', $taxquery );
}
}
}
add_action('pre_get_posts','search_filter');
如果您想排除小部件类别中的类别,请复制以下代码:
<?php
function custom_category_widget($args) {
$exclude = "244"; // Category IDs to be excluded
$args["exclude"] = $exclude;
return $args;
}
add_filter("widget_categories_args","custom_category_widget");
上面的代码在 Wordpress 6.0 和 Avada 7.7.1 主题中对我有用
我希望我能帮上忙,有什么事写信给我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.