如何循环自定义帖子类型并返回每个自定义分类

时间:2018-03-30 20:09:59

标签: wordpress wordpress-theming

我有一个自定义的帖子类型(artwork)用于艺术作品,我已经为这件艺术品所属的每个时期注册了一个自定义分类(period)。例如,艺术品&#34 ;星夜"将属于" 1880 - 1889"期。

我需要的是能够遍历CPT并返回主页上的每个period。然后,这将链接到该时期的存档。我一直试图寻找这个,但由于有关CPT的文献数量很难找到答案。

我已经使用this资源尝试自己解决这个问题,但是还没有能力。

1 个答案:

答案 0 :(得分:1)

如果您只是列出包含档案链接的条款,为什么还需要浏览帖子/ CPT?

您可以使用 get_terms() 函数返回WP_Term个对象数组:

$args = array(
    'taxonomy' => 'period',
    'hide_empty' => true,
);

if( $terms = get_terms( $args ) ){
    echo '<ul>';
        foreach( $terms as $term ){
            $url = get_term_link( $term->slug, 'period' );
            echo "<li><a href=\"$url\">{$term->name} ({$term->count})</a></li>";
        }
    echo '</ul>';
}

/**
 * Output:
 *
 * <ul>
 *   <li><a href="/period/80-89">1880-1889 (1)</a><li>
 *   <li><a href="/period/90-99">1890-1899 (3)</a><li>
 * </ul>
 */

如果由于某种原因你想要浏览你的帖子,你需要 get_the_terms() ,并把它放在你的循环中,这将获得与之相关的所有术语那篇文章:

  

&#13;
&#13;
    // Loop started above

	if( $terms = get_the_terms( $post->ID, 'period' ) ){
		echo '<ul>';
			foreach( $terms as $term ){
				$url = get_term_link( $term->slug, 'period' );
				echo "<li><a href=\"$url\">{$term->name} ({$term->count})</a></li>";
			}
		echo '</ul>';
	}

    // Finish loop below
&#13;
&#13;
&#13;