投稿タイプ別記事一覧表示

PHP
function display_custom_post_types_with_linked_taxonomies($atts)
{
	// ショートコードの属性を設定
	$atts = shortcode_atts(array(
		'post_types'     => '', // 表示したい投稿タイプ (カンマ区切りで指定)
		'posts_per_type' => 5, // 各投稿タイプの表示件数 (デフォルト: 5)
	), $atts);

	// 投稿タイプをカンマ区切りで取得して配列化
	$selected_post_types = array_filter(array_map('trim', explode(',', $atts['post_types'])));

	// 投稿タイプが空の場合は公開されているすべてを取得 (attachmentは除外)
	if (empty($selected_post_types)) {
		$post_types = get_post_types(array(
			'public' => true,
		), 'names');
		unset($post_types['attachment']); // メディアを除外
	} else {
		// 指定された投稿タイプだけを使用
		$post_types = array_intersect($selected_post_types, get_post_types(array(
			'public' => true,
		), 'names'));
	}

	$output = '<div class="post-type-wrapper">'; // ラッパーを開始

	foreach ($post_types as $post_type) {
		// 各投稿タイプの投稿を取得
		$posts = get_posts(array(
			'post_type'      => $post_type,
			'posts_per_page' => intval($atts['posts_per_type']), // 属性で指定した件数
			'orderby'        => 'modified', // 更新日順に並べ替え
			'order'          => 'DESC',     // 降順 (最新の更新日が上)
		));

		if (!empty($posts)) {
			foreach ($posts as $post) {
				$output .= '<div class="post-type-card">';
				$output .= '<a href="' . get_permalink($post->ID) . '"><strong>' . esc_html($post->post_title) . '</strong></a>';
				$output .= '<p class="post-meta">';
				$output .= '<span class="post-modified">更新日: ' . get_the_modified_date('Y-m-d', $post->ID) . '</span>';
				$output .= '<span class="post-date">公開日: ' . get_the_date('Y-m-d', $post->ID) . '</span><br>';

				// カテゴリーリンクを作成
				$categories = get_the_category($post->ID);
				if (!empty($categories)) {
					$output .= '<span class="post-category">カテゴリー: ';
					$category_links = array();
					foreach ($categories as $category) {
						$category_links[] = '<a href="' . get_category_link($category->term_id) . '">' . esc_html($category->name) . '</a>';
					}
					$output .= implode(', ', $category_links) . '</span><br>';
				}

				// カスタムタクソノミーリンクを作成
				$taxonomies = get_object_taxonomies($post_type, 'objects'); // 投稿タイプに紐付くタクソノミーを取得
				foreach ($taxonomies as $taxonomy_slug => $taxonomy) {
					$terms = get_the_terms($post->ID, $taxonomy_slug);
					if (!empty($terms)) {
						$output .= '<span class="post-taxonomy">' . esc_html($taxonomy->label) . ': ';
						$term_links = array();
						foreach ($terms as $term) {
							$term_links[] = '<a href="' . get_term_link($term->term_id, $taxonomy_slug) . '">' . esc_html($term->name) . '</a>';
						}
						$output .= implode(', ', $term_links) . '</span><br>';
					}
				}

				$output .= '</p>';
				$output .= '</div>';
			}
		}
	}

	$output .= '</div>'; // ラッパーを閉じる

	return $output; // HTMLを返す
}

// ショートコードを登録
add_shortcode('selected_post_types', 'display_custom_post_types_with_linked_taxonomies');