カスタム投稿タイプを含む、投稿の一覧をページの様々な箇所で表示させる

カスタム投稿タイプを含む、投稿の一覧をページの様々な箇所で表示させるのアイキャッチ画像

カスタム投稿タイプを含む様々な投稿の一覧を、呼び出す方法です。get_postsを使うクエリに影響を与えない 方法です。

カスタム投稿タイプ

カスタム投稿タイプのアーカイブ

カスタム投稿タイプのアーカイブを出力する場合。カレントページを除外しない場合はパラメーターを削除するか''空にしておきます。

<?php $args = array(
	'posts_per_page'   => 5, //表示件数
	'offset'           => 0,
	'orderby'          => 'date',
	'order'            => 'DESC',
	'exclude'          => $post->ID, //カレントページを除外
	'post_type'        => '投稿タイプ',
	'post_status'      => 'publish',
	'suppress_filters' => true
);
$posts_array = get_posts( $args ); ?>
<?php foreach ( $posts_array as $post ) : setup_postdata( $post ) ;?>
//処理
<?php endforeach; wp_reset_postdata(); ?>

タームのアーカイブ

タームのアーカイブを出力する場合

<?php $args = array(
	'posts_per_page'   => 5,
	'offset'           => 0,
	'orderby'          => 'date',
	'order'            => 'DESC',
	'exclude'          => $post->ID,
	'post_type'        => 'news',
  'tax_query' => array(
    array(
      'taxonomy' => 'タクソノミー名',
      'field' => 'slug',
      'terms' => 'ターム名'
    )
  ),
	'post_status'      => 'publish',
	'suppress_filters' => true
);
$posts_array = get_posts( $args ); ?>
<?php foreach ( $posts_array as $post ) : setup_postdata( $post ) ;?>
//処理
<?php endforeach; wp_reset_postdata(); ?>

今いるタームの一覧

詳細ページで今いるタームの一覧

<?php
$custom_post_name = get_query_var('post_type');
$cp_tax = get_object_taxonomies($custom_post_name);
$my_tax = $cp_tax[0];
$create_tax = get_the_terms($post->ID, $my_tax);
$tax_slug = $create_tax[0]->slug;
$args = array(
'numberposts' => 10,
'post_type' => $cpt,
'tax_query' => array(
  array(
    'taxonomy' => $my_tax,
    'field' => 'slug',
    'terms' => $tax_slug,
  )
),
'orderby'   => 'date',
'order'     => 'DESC' //降順
);
$customPosts = get_posts($args);
if($customPosts) : foreach($customPosts as $post) : setup_postdata( $post );
?>

通常の投稿の場合

通常の投稿のカテゴリーを出力する場合

  <?php $args = array(
  'posts_per_page'   => 5,
  'offset'           => 0,
  'category'         => '',
  'category_name'    => 'カテゴリースラッグ',
  'orderby'          => 'date',
  'order'            => 'DESC',
  'exclude'          => $post->ID,
  'post_type'        => 'post',
  'post_status'      => 'publish',
  'suppress_filters' => true
  );
  $posts_array = get_posts( $args ); ?>
  <?php foreach ( $posts_array as $post ) : setup_postdata( $post ); ?>
    //処理
  <?php endforeach; wp_reset_postdata(); ?>