【问题标题】:Parent categories and child categories posts父类别和子类别帖子
【发布时间】:2012-05-31 14:32:40
【问题描述】:

我有代码可以显示每个类别(包括子类别)的最新 3 个帖子,我想从这些子类别中排除帖子,因为这些帖子已经显示在父类别中。

例如,我将打印机类别作为父类别,将(打印机配件、.....、.....)作为子类别。
所以它显示了每个最新的 3 个帖子,我想排除任何子类别(打印机配件、.....、....)及其帖子。

代码如下:

$cat_args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'child_of' => 0
);

$categories =   get_categories($cat_args); 

foreach($categories as $category) {
    echo '<dl>';
    echo '<dt> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all items in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></dt>';

     $post_args = array(
      'numberposts' => 3,
      'category' => $category->term_id
    );

    $posts = get_posts($post_args);

    foreach($posts as $post) {
    ?>
        <dd>
                    <div class="allincat">

                    <div class="catmeta">                    
                    <span class="authinfo"> 
                    <div class="authimg"></div>
                     <?php the_author(); ?> | <?php the_time('jS F Y') ?> </span>


                    </div>

                    <div class="allincatimg">
                    <?php the_post_thumbnail(array(50,50)); ?> </div>
                    <div class="allincattit">                    
                    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </div>





                    </div>

                    </dd>
    <?php
    }
    echo '<div class="view-all"> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all items in %s" ), $category->name ) . '" ' . '>View all items in ' . $category->name.'</a></div>';
    echo '</dl>';
}

【问题讨论】:

    标签: wordpress


    【解决方案1】:

    在构建参数数组后查询帖子。

    <?php
        $args = array(
            'cat'      => 22, // your parent cat id here 
            'order'    => 'ASC'
            'orderby' => 'name',
            'posts_per_page' => 3
        );
    
        query_posts( $args ); ?>
    
              <?php if (have_posts()) : ?>
                <?php while (have_posts()) : the_post(); ?>
                  <dd>
                    <div class="allincat">
                      <!-- content here -->
                    </div>
                  </dd>
                <?php endwhile; ?>
              <?php endif; ?>
    

    【讨论】:

    • 谢谢,但这将由 id 为站点中的每个父类别定义,但我希望自动为我的所有父类别而不是 id 定义,因为父类别可能会在以后更多。有什么解决办法吗?
    • 然后使用$cat_ID = get_query_var('cat');动态获取当前类别ID
    • 你能解释一下这个解决方案吗
    • 它将查询特定类别并仅从该类别中检索帖子。它使用标准的 wordpress 循环。
    • 好的,请您在您的解决方案中编写代码,因为我不知道具体在哪里,谢谢
    猜你喜欢
    • 2013-01-24
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-30
    相关资源
    最近更新 更多