显示自定义帖子类型/分类中所有类别的最新x篇帖子

时间:2015-07-07 作者:bigdaveygeorge

我试图在WordPress中使用一种称为“案例研究”的自定义分类法来显示所有类别的最新x帖子。

我已经成功地将所有类别名称输出为标题链接。我还输出了一些来自标准帖子分类法的帖子,这些帖子属于正确的类别,但我无法显示我的“案例研究”分类法中的任何内容。当我添加\'post_type\' => \'case-studies\'$post_args 查询它不显示任何结果。

if (have_posts()) :

    $tax = \'case-studies\';

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

    $categories = get_terms($tax, $cat_args);

    foreach($categories as $category) {

        echo \'<p><a href="\' . get_term_link( $category, $tax ) . \'" title="\' 
            . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' 
            . \'>\' . $category->name.\'</a></p>\';

        $post_args = array(
            \'posts_per_page\' => 10,
            \'category_name\' => $category->name
        );

        $posts = get_posts($post_args);

        foreach($posts as $post) { ?>
            <a href="<?php echo get_the_permalink(); ?>"><?php echo get_the_title(); ?></a><br/>
        <?php }

        echo \'<p><a href="\' . get_term_link( $category, $tax ) . \'" title="\' 
            . sprintf( __( "View all posts in %s" ), $category->name ) . \'" \' 
            . \'>View all posts in \' . $category->name.\'</a></p>\';
    }

endif;

2 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

类别参数不适用于自定义分类法。您需要使用tax_query 相反

在当前代码中,替换(,它在任何情况下都被错误使用,category_name 采用slug, 不name)

\'category_name\' => $category->name
使用

\'post_type\' => \'case-studies\',
\'tax_query\' => array(
    array(
        \'taxonomy\' => $tax
        \'terms\' => $category->term_id,
        \'include_children\' => false
    )
),

SO网友:Kd dev

此代码显示所有类别的所有帖子location taxonomy 对于custom post type testaismgallery.

 $args = array(
        \'number\'     => $number,
        \'hide_empty\' => $hide_empty,
        \'include\'    => $ids
    );

    $custom_categories = get_terms( \'location\', $args );

    foreach ( $custom_categories as $catterm){

        $arg = Array( 
        \'post_type\' => \'testaismgallery\',
        \'posts_per_page\' => \'-1\',
        \'post_status\' => \'publish\',
        \'tax_query\' => Array( Array ( 
        \'taxonomy\' => \'location\' ,
        \'terms\' => $catterm->term_id
        )) );


    $loop = new WP_Query( $arg ); 
    global $post;

    ?>    

    <?php    
    while ( $loop->have_posts() ) : $loop->the_post();
    ?>
      <div class="gallery-content">
    <div class="entry-content">


    <?php 
    $post_id = get_the_ID();
    $abc = get_post_meta($post_id, event_file, true);
     echo "<li><img src=\'".$abc. "\' ></li> "; 

     ?>  

        </div>
    </div>
     <?php endwhile;

    }   

    ?>

结束