【WordPress】 カスタム投稿タイプでターム一覧を取得するサブループの書き方(get_posts() とWP_Queryの2通り)

wordpress

カスタム投稿タイプのterm一覧を出力する場合のコードです。

get_posts()を使用した場合、ページネーションが設定できないことを知らなかったため、結局WP_Queryで書き直すことに;;

どうせなら比較のために両方のコードを掲載しようと思いまして。

get_posts()を使用した場合

<?php
$custom_posts = get_posts(array(
	'post_type' => 'topics',
	'posts_per_page' => 3,
	'tax_query' => array(
		array(
		'taxonomy' => 'topics-cat',//タクソノミー名を指定
		'field' => 'slug',
		'terms' => 'news'//タームを指定
		)
	)
	));
	global $post;
	if ($custom_posts) : foreach ($custom_posts as $post) : setup_postdata($post); ?>

	<li>
		<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
		<p><?php the_time('Y/m/d') ?></p>
		<p><?php the_excerpt(); ?></p>
	</li>

<?php endforeach;
	wp_reset_postdata();
endif; ?>

WP_Queryの場合

<?php
$args = array(
  'post_type' => 'topics',
 'posts_per_page' => 9,
 'order' => 'DESC',
  'tax_query' => array(
    array(
     'taxonomy' => 'topics-cat',//タクソノミー名を指定
      'field' => 'slug',
      'terms' => 'column'//タームを指定
    )
)
);
$my_query = new WP_Query($args);

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

<li>
	<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
	<p><?php the_time('Y/m/d') ?></p>
	<p><?php the_excerpt(); ?></p>
</li>

<?php endwhile;
wp_reset_postdata();
endif; ?>

追加:ページネーションを出力する場合のWP_Queryを使用したサブループのコード例

<?php

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
  'post_type' => 'topics',
 'posts_per_page' => 9,
 'order' => 'DESC',
 'paged' => $paged,
  'tax_query' => array(
    array(
     'taxonomy' => 'topics-cat',//タクソノミー名を指定
      'field' => 'slug',
      'terms' => 'column'//タームを指定
    )
)
);
$my_query = new WP_Query($args);

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

<div>
	<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
	<p><?php the_time('Y/m/d') ?></p>
	<p><?php the_excerpt(); ?></p>
</div>

<?php endwhile; ?>
<?php endif; ?>

<div class="pagination">
<?php
$args = array(
'mid_size' => 1,
'prev_text' => 'BACK',
'next_text' => 'NEXT',
screen_reader_text' => ' ',
);
the_posts_pagination($args);
?>
</div><!--pagenation-->

<?php wp_reset_query(); ?>
wordpress
スポンサーリンク
Web Parts Box
タイトルとURLをコピーしました