アイキャッチ画像付きのカスタム投稿タイプ一覧

カスタム投稿タイプの一覧を、ターム名、日付、サムネイル付きで表示します。
カスタム投稿タイプは複数指定することも可能です。
<ul> <?php $args = array( 'posts_per_page' => 5, // 表示する投稿数 'post_type' => array('posttype_1', 'posttype_2'), // 取得する投稿タイプのスラッグ 'orderby' => 'date', //日付で並び替え 'order' => 'DESC' // 降順 or 昇順 ); $my_posts = get_posts($args); ?> <?php foreach ($my_posts as $post) : setup_postdata($post); ?> <li> <a href="<?php echo get_permalink($post->ID); ?>"> <?php // アイキャッチ画像を取得 $thumbnail_id = get_post_thumbnail_id($post->ID); $thumb_url = wp_get_attachment_image_src($thumbnail_id, 'small'); if (get_post_thumbnail_id($post->ID)) { echo '<figure><img src="' . $thumb_url[0] . '" alt=""></figure>'; } else { // アイキャッチ画像が登録されていなかったときの画像 echo '<figure><img src="' . get_template_directory_uri() . '/img/img-default.png" alt=""></figure>'; } ?> <?php // ターム名を表示 $terms = get_the_terms($post->ID, 'tax_name_1'); // タームが所属するタクソノミースラッグを指定 if (!empty($terms)) { // タームが複数選択されていたらカンマ区切りで表示 $output = array(); foreach ($terms as $term) { if ($term->parent != 0) $output[] = $term->name; } if (count($output)) { echo '<span class="term">' . join(", ", $output) . '</span>'; } else { echo '<span class="term">' . $term->name . '</span>'; } } ?> <p> <span class="date"><?php the_time('Y.m.d') ?></span> <?php echo get_the_title($post->ID); ?> </p> </a> </li> <?php endforeach; ?> <?php wp_reset_postdata(); ?> </ul>
タームごとにカスタム投稿タイプの一覧を表示する

指定したタクソノミーに属するタームの記事を、タームごとに表示する方法です。
タームの増減があれば、自動的に反映されます。
<?php $taxonomy_name = 'tax_name'; // タクソノミーのスラッグ名を入れる $post_type = 'posttype_1'; // カスタム投稿のスラッグ名を入れる $args = array( 'order' => 'DESC', ); $taxonomys = get_terms( $taxonomy_name, $args); if(!is_wp_error($taxonomys) && count($taxonomys)): foreach($taxonomys as $taxonomy): $tax_posts = get_posts( array( 'post_type' => $post_type, 'posts_per_page' => -1, // 表示させたい記事数 'tax_query' => array( array( 'taxonomy' => $taxonomy_name, 'terms' => array( $taxonomy->slug ), 'field' => 'slug', 'include_children' => true, //子タクソノミーを含める ) ) )); if( $tax_posts ) : ?> <h2><?php echo esc_html($taxonomy->name); ?></h2> <ul> <?php foreach($tax_posts as $tax_post): ?> <li> <a href="<?php echo get_permalink($tax_post->ID); ?>"><?php echo get_the_title($tax_post->ID); ?></a> </li> <?php endforeach; wp_reset_postdata(); ?> </ul> <?php endif; endforeach; ?> <?php else: ?> <p>投稿はありません</p> <?php endif; ?>
get_postsの各種クエリについてはWordPress私的マニュアルさんに詳しく書かれています。