获取自定义帖子类型子类别

时间:2015-10-14 14:24:36

标签: php wordpress categories

我必须回复所有类别,其中包含我自己创建的自定义帖子类型中的帖子。我目前有三个类别,我需要它,因为我可能会添加另一个类别,这就是为什么我不必深入编码以显示另一个查询。

风格:

- Category title
-- category post title, content etc.

- Category2 title
-- Category2 post contents

我当前的代码看起来像那样

        <?php
        $args=array(
          'post_type' => 'edasimja'
        );
        $my_query = null;
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {
          while ($my_query->have_posts()) : $my_query->the_post(); ?>

        <div class="col-sm-4">
            <?php $c = get_the_category(); ?>
            <?php echo $c[0]->cat_name; ?>
          <h2><?php the_title(); ?></h2>
          <?php the_field('eli'); ?>
        </div>

            <?php
          endwhile;
        }
        wp_reset_query();
        ?>

此代码分别使用其cat名称查询每个帖子,但我需要一个包含每个类别的列。我似乎无法实现这一目标。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

所以,我找到了解决方案。

    <?php

    $post_type = 'features';
    $taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) );

    foreach( $taxonomies as $taxonomy ) :

// Gets every "category" (term) in this taxonomy to get the respective posts
$terms = get_terms( $taxonomy );

foreach( $terms as $term ) : ?>

    <section class="category-section">

    <div class="row">
    <div class="span12">
        <h2 class="mid-heading"><?php echo $term->name; ?></h2>
    </div>

    <?php
    $args = array(
            'post_type' => $post_type,
            'posts_per_page' => -1,  //show all posts
            'tax_query' => array(
                array(
                    'taxonomy' => $taxonomy,
                    'field' => 'slug',
                    'terms' => $term->slug,
                )
            )

        );
    $posts = new WP_Query($args);

    if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?>

        <div class="span4">

            <article class="inner-post clearfix">

                <div class="inner-img whitebox">
                <?php if(has_post_thumbnail()) { ?>
                        <?php the_post_thumbnail(); ?>
                <?php }
                /* no post image so show default */
                else { ?>
                       <img src="<?php bloginfo('template_url'); ?>/assets/img/default-img.png" alt="<?php echo get_the_title(); ?>" title="<?php echo get_the_title(); ?>" width="110" height="110" />
                <?php } ?>
                </div>

                <div class="inner-content">

                <h3 class="heading-size-14 font-weight-600"><a href="<?php echo get_permalink(); ?>" title="Read more about <?php echo get_the_title(); ?>"><?php  echo get_the_title(); ?></a></h3>

                    <?php the_excerpt(); ?>
                </div>
            </article><!-- about-box -->


        </div>

    <?php endwhile; endif; ?>
    </div>
    <hr>
    </section>

<?php endforeach;

endforeach; ?>