【问题标题】:Exclude category Wordpress (WP_Query not working)排除类别 Wordpress(WP_Query 不起作用)
【发布时间】:2015-03-16 00:18:28
【问题描述】:

谁能解释为什么这个查询不起作用? 我想排除带有主页标记的帖子。 它仍然显示类别名称为“主页”的帖子...

<?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; ?>

【问题讨论】:

  • 也试过 $query = new WP_Query( 'cat=-11' );但它也不起作用。
  • 不相关...但是伙计,摆脱所有那些&lt;?php ?&gt;标签...
  • 你还需要把while ( have_posts() ) : the_post();改成while ( $query-&gt;have_posts() ) : $query-&gt;the_post();
  • 谢谢内森!好像是这个问题!我忽略了它!
  • @rnevius 我该怎么做? (还在学习中……)

标签: php wordpress


【解决方案1】:

如文档中所述,在排除类别的情况下,您必须使用其 ID 而不是 slug(检查 here)。

你可以试试:

$query = new WP_Query( array( 'category__not_in' => array( 11 ) ) );

【讨论】:

  • 您确定没有任何主题设置可以覆盖排除类别吗?
  • 谢谢 Nathan 和 Grzegorz!
【解决方案2】:

您的代码中有 2 个问题。

您使用 slug 而不是 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多