WordPress のカスタムタクソノミーの分類毎に記事を出力する方法

WordPress のカスタムタクソノミーの分類ごとに記事を出力するには以下のようにします。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
$taxonomy_name = 'news_type';
$taxonomys = get_terms($taxonomy_name);
if(!is_wp_error($taxonomys) && count($taxonomys)):
	foreach($taxonomys as $taxonomy):
		$tax_posts = get_posts(array('post_type' => get_post_type(), 'taxonomy' => $taxonomy_name, 'term' => $taxonomy->slug ) );
		if($tax_posts):
?>
		<div class="category">
			<h2><?php echo esc_html($taxonomy->name); ?></span></h2>
			<ul>
				<?php foreach($tax_posts as $tax_post): ?>
				<li><a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo esc_html($tax_post->post_title); ?></a></li>
				<?php endforeach; ?>
			</ul>
		</div>
<?php
		endif;
	endforeach;
endif;
?>

3行目: $taxonomys = get_terms($taxonomy_name);

これは $taxonomy_name に登録されている分類を取得します。

3
$taxonomys = get_terms($taxonomy_name);

参考に $taxonomys の中身を展開すると以下のようになっています。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Array
(
    [0] => stdClass Object
        (
            [term_id] => 5
            [name] => テストA
            [slug] => testa
            [term_group] => 0
            [term_taxonomy_id] => 5
            [taxonomy] => news_type
            [description] => 
            [parent] => 0
            [count] => 2
        )
 
    [1] => stdClass Object
        (
            [term_id] => 3
            [name] => テストB
            [slug] => testb
            [term_group] => 0
            [term_taxonomy_id] => 3
            [taxonomy] => news_type
            [description] => 
            [parent] => 0
            [count] => 2
        )
 
)

foreach() などで回せばタクソノミー一覧になるということです。

6行目: $tax_posts = get_posts();

6行目は記事を取得しています。以下の場合ですと現在のカスタム投稿タイプのタクソノミーが $taxonomy_name であり、分類が $taxonomy->slug である記事を取得します。

6
$tax_posts = get_posts(array('post_type' => get_post_type(), 'taxonomy' => $taxonomy_name, 'term' => $taxonomy->slug));

コメント

コメントは受け付けていません。