如何使用wp_query获取特定的子类别帖子

时间:2016-12-08 04:14:55

标签: wordpress bootstrap-modal categories

我有一个模态类别,在我的模态类别中,我有三个子类别。这是我的模态类别的结构。

-Modal
  -Water Pumps
  -Water Heaters
  -Electrical

在这里,我想从我的模态类别中获取水泵子类别中的帖子并显示在我的模态中。这是我的代码,它显示了所有类别名称为模态的代码,如何将其限制为类别名称模式和水泵的子类别

<div id="myModal38" class="modal fade" tabindex="-1">
<?php $args1 = array(
                    'post_type' => 'post',
                    'category_name' => 'modal',
                    'posts_per_page' => '1',
                );
    $modalPost = new WP_Query( $args1 );
    if( $modalPost->have_posts() ) : 
?>
    <div class="modal-dialog">
    <?php while ( $modalPost->have_posts() ) : $modalPost->the_post(); ?>
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" type="button" data-dismiss="modal">×</button>
                    <h4 class="modal-title"><?php the_title(); ?></h4>
            </div>
            <div class="modal-body">
                <?php the_post_thumbnail(); ?>
                <?php the_content(); ?>
    <?php endwhile; ?>
            </div>
    <?php endif; ?>
    <?php wp_reset_postdata(); ?>       
            </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Modal -->

2 个答案:

答案 0 :(得分:0)

如果要加载“模态”和“水泵”类别中的帖子,可以使用以下WP查询参数:

$args1 = array(
        'post_type' => 'post',
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'include_children' => false,
                'field' => 'name',
                'terms'    => array('Modal', 'Water Pumps')
            )
        )
    );

include_children选项设置为false,因此它不会加载其余的Modal子类别。 按照您的示例,代码按名称加载类别,但是使用ID可能更安全并删除'field' => 'name'选项,以便在重命名类别时代码仍然有效。

答案 1 :(得分:0)

从特定的父类别中查询特定的子类别。提供此功能是因为@Ben的答案无法正常工作。

$args1 = array(
        'post_type' => 'post', 
        'post_status' => 'publish',
        'category_name' => 'Modal',
        'posts_per_page' => 3,
        'tax_query' => array(
                            array(
                                'taxonomy' => 'category',
                                'include_children' => false,
                                'field' => 'name',
                                'terms'    => array('Water Pumps')
                            ),
                        ),
         );

        $modalPost = new WP_Query( $args1 );