从WordPress帖子中排除类别


exclude category from wordpress post

我想从我的博客文章中排除类别。我的类别 ID 是 62。类别名称为perfect_work

这是我的WordPress博客模板代码:

    <div id="left" class="eleven columns">
    <?php
    $temp = $wp_query;
    $wp_query= null;
    $wp_query = new WP_Query();
    $wp_query->query('paged='.$paged);
    ?>
    <?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
        <div class="post" id="post-<?php the_ID(); ?>">
            <div class="title">
                <h2><a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>" ><?php the_title(); ?></a></h2>
                <div class="postmeta">  <span>by <?php the_author_posts_link(); ?></span> | <span><?php the_time('l, F jS, Y') ?></span> | <span><?php the_category(', '); ?></span> </div>
            </div>
            <div class="entry">
            <?php $image_attr = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'top_feature'); ?>    
                <a href="<?php the_permalink() ?>"><img src="<?php echo $image_attr[0]; ?>" class="postim scale-with-grid" id="blog-thumb" ></a>
                <?php wpe_excerpt('wpe_excerptlength_archive', ''); ?>
                <div class="clear"></div>
            </div>
        </div>
    <?php endwhile; ?>
    <?php getpagenavi(); ?>
    <?php $wp_query = null; $wp_query = $temp;?>
</div>

我已经尝试使用

$wp_query = new WP_Query('cat=-62');

它不起作用。我也把

<?php query_posts('cat=-62'); ?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

它的工作,但页面导航不起作用,也没有显示其他人的帖子。 只有 1st 5 帖子显示。

有什么解决方案吗?

获取页码

$paged = get_query_var('paged') ? get_query_var('paged') : 1;

然后你可以使用

$wp_query = new WP_Query('cat=-62&paged=' . $paged);

或使用

$cat_id = get_cat_ID('perfect_work');
$wp_query = new WP_Query('cat=-' . $cat_id . '&paged=' . $paged);

然后循环

if($wp_query->have_posts()) :
    while ($wp_query->have_posts()) : $wp_query->the_post();
        // ...
    endwhile;
endif;

试试这个,你必须指定showposts来限制帖子

<?php $wp_query->set( 'cat', '-62' ); ?>
<?php query_posts( 'showposts=10' ); ?> 
<?php if( have_posts() ) : ?> 
<?php while( have_posts() ) : the_post(); ?>
.
.
.
<?php endwhile; ?>
<?php endif; ?>

注意:减号表示排除所有帖子 从数据库中检索到属于该类别。在 转,循环将永远不会有该类别 ID 的帖子,并且只有 处理指定数量的其他类别 ID 的帖子。

请阅读WP_Query上的手抄本,它非常详细,看看类别参数部分

只需在你不需要的类别前面添加一个减号-,所以下面的代码意味着显示类别 10 和 11 的帖子,但不包括类别 62

$recent = new WP_Query("showposts=3&cat=10,11,-62")

无需在查询之前或之后使用 $temp 变量。你应该使用这样的东西:

//This should do the trick
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
    'cat' => -62,
    'paged' => $paged
);
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
  <!-- the loop -->
  <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <h2><?php the_title(); ?></h2>
  <?php endwhile; ?>
  <!-- end of the loop -->
  <!-- pagination here -->
  //The real trick!
  <?php wp_reset_postdata(); ?>

需要注意的两件事:

  • 分页查询参数
  • 要重置查询,请使用wp_reset_postdata()