首页 > WordPress学习 > WordPress制作分类模板调用其他分类信息时 如何排除当前分类数据

WordPress制作分类模板调用其他分类信息时 如何排除当前分类数据

时间:2022年11月23日 分类:WordPress学习 浏览量:299

我们在制作分类模板时,分类列表右侧往往会放一些其他分类的信息,比如热门、最新、随机等,那么这些地方数据调用,如何排除当前分类数据呢?

        <?php 
        $catid = $cat->cat_ID;
        $args=array(
            'category__not_in' => array($catid),
            'posts_per_page' => 5,
            );
        $newpost = new WP_Query($args);
        if ( $newpost -> have_posts() ): while ( $newpost -> have_posts() ) : $newpost ->the_post(); ?>
        <li>
        <a href="<?php the_permalink(); ?>">
          <h4><?php the_title(); ?></h4>
          <span><i class="fa fa-calendar"></i><?php the_time('Y-n-j'); ?></span>
        </a>
        </li>
        <?php  endwhile; endif; wp_reset_query(); ?>

第一种方法,实验失败,无法排除当前分类的数据,这里$catid = $cat->cat_ID无效;改一种方式:

        <?php 
        $catid = get_queried_object_id();
        $args=array(
            'category__not_in' => array($catid),
            'posts_per_page' => 5,
            );
        $newpost = new WP_Query($args);
        if ( $newpost -> have_posts() ): while ( $newpost -> have_posts() ) : $newpost ->the_post(); ?>
        <li>
        <a href="<?php the_permalink(); ?>">
          <h4><?php the_title(); ?></h4>
          <span><i class="fa fa-calendar"></i><?php the_time('Y-n-j'); ?></span>
        </a>
        </li>
        <?php  endwhile; endif; wp_reset_query(); ?>

使用get_queried_object_id()来获取当前分类ID,成功实现当前分类数据排除;

get_queried_object_id()函数,用于检索当前查询对象的ID,支持分类页、自定义分类法创建的分类、标签页、文章页、自定义文章类型创建的文章、单篇页面。返回值只有一个,即当前页面的ID。

除了这个简便方法,还可以使用$catid = get_query_var(‘cat’);来定义当前分类ID。

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权

文章名称:WordPress制作分类模板调用其他分类信息时 如何排除当前分类数据

文章链接:https://news.yynnw.com/128.html

该作品系作者结合个人学习经验及互联网相关知识整合。如若侵权请通过投诉通道提交信息,我们将按照规定及时处理。

觉得文章有用就打赏一下文章作者

微信扫一扫打赏

标签:

最新文章

猜你喜欢