【问题标题】:how to get only parent category posts in wordpress如何在wordpress中仅获取父类别帖子
【发布时间】:2018-03-09 19:45:46
【问题描述】:

我想在首页获得唯一的顶级父类别(cat_id=1)列表。 为此,我在主页中编写了这个 While 循环。

<div class="left col-xs-12 col-md-8 col-lg-9">
        <?php
            while(have_posts()) {
                the_post(); ?>
                <div class="content-block col-xs-12">
                    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <hr class="color-strip">
                    <p><?php echo wp_trim_words(get_the_content(), 11); ?></p>
                    <p><a href="<?php the_permalink(); ?>">Continue reading &raquo;</a></p>
                    <div class="tags"><ul><li><?php the_tags(); ?></li></ul></div>
                </div>
                <hr/>
        <?php }?>

    </div>

但它也带来了所有子类别。我想只保留一个类别的列表。我必须对 if 条件进行什么更改。

【问题讨论】:

  • 我在您发布的代码中没有看到 if 语句。这是整个代码示例吗?另外,您是如何检索帖子的?
  • 是的,我正在寻找我必须在 if 条件下连接的内容,以仅带来 cat_id=1 中的内容。 cat _id=1 有很多子类别,他们有很多帖子。但我只想要父母中的东西

标签: wordpress while-loop


【解决方案1】:

您可以使用get_categories() 获取类别,并且您可以使用以下方式获取所有顶级类别:

$categories = get_categories(
    array(
        'parent' => 0
    )
);

那么,这样的事情应该可以让您只获取顶级类别中的帖子。

$categories = get_categories(
    array(
        'parent' => 0
    )
);

$categoryArray = array();

foreach( $categories as $category ) {
    $categoryArray[] = $category->ID;
}

function exclude_category($query) {
    if ( $query->is_home() ) {
        $query->set( 'cat', implode(',', $categoryArray) );
    }
    return $query;
}
add_filter('pre_get_posts', 'exclude_category');

这将获取所有顶级类别,然后在主查询中设置它们。

【讨论】:

    【解决方案2】:

    以下鳕鱼部分解决了我的问题。在functions.php中编写一个函数。

    function exclude_category($query) {
        if ( $query->is_home() ) {
        $query->set('cat', '-5,-6');
        }
        return $query;
        }
        add_filter('pre_get_posts', 'exclude_category'); 
    

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      相关资源
      最近更新 更多