スポンサーリンク

投稿の一覧を表示するショートコードを作成する方法

WordPressで、記事の一覧を表示したい場合は、テーマについている機能や、プラグインを使って表示をすると思いますが、簡単に自作をすることが可能です。

以下のような一覧の作成をするサンプルです。

ソースコード

以下のソースコードを、functions.phpへコピペしてください。

function customInfomationList($atts) {
	
	$pairs = [
		'num' => 5,
		'category_name' => null
	];
	
	$atts = shortcode_atts($pairs, $atts);
	
	// 引数
	$args = [
    'posts_per_page' => $atts['num'],
		'category_name' => $atts['category_name']
	];
	
	$post_query = new WP_Query($args);
	
	$output = "";
	
	if ($post_query->have_posts()) {
		
		while($post_query->have_posts()) {
			
			$post_query->the_post();
			
			$output .= '<article class="custom-info-box">';
			$output .= '<section>';
			$output .= '<a href="' . get_permalink() . '">' . get_the_post_thumbnail(get_the_ID(), 'thumbnail') . '</a>';
			$output .= '<p class="custom-info-day">' . get_the_date('Y年m月d日') . '</p>';
			$output .= '<div class="custom-info-title">';
			$output .= '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
			$output .= '</div>';
			$output .= '</section>';
			$output .= '</article>';
		}
	}
	
	wp_reset_query();
	
	return $output;
}

add_shortcode('custom_infomation_list', 'customInfomationList');

43行目でショートコードとして使えるようにしています。

CSS

CSSは、使用しているテーマや、ご自身で設定をしたスタイルによりだいぶ変わってくると思います。以下は参考にしてください。

パソコン画面では2列に並べて表示をしたいので、custom-info_wrapperクラス(HTMLで出てきます)で、flexを使用し、custom-info-boxクラスで、flex-basis: 45%としています。

.custom-info_wrapper {
	display: flex;
	flex-wrap: wrap;
	justify-content: space-around;
}

.custom-info-box {
	padding: 1em;
  margin: .5em .5em;
	text-align: center;
	border: 1px solid #C0C0C0;
	flex-basis: 45%;
}

div.custom-info-title {
	margin-bottom: 0;
	margin-top: 10px;
	text-align: left;
}

div.custom-info-title h3 {
	font-size: 1em;
	margin-top: 0 !important;
	margin-bottom: 0 !important;
	margin-left: 0 !important;
	padding: 0;
	border:none;
}

p.custom-info-day {
	margin-bottom: 0;
	margin-top: 0;
	text-align: left;
}

p.custom-info-day {
	font-size: 0.8em;
	color: #A5A5A5;
}

HTML

カスタムHTMLで以下のように記載をします。

<div class="custom-info_wrapper">
[custom_infomation_list num=10]
</div>

引数の、「num」で、表示したい投稿の数を設定することができます。

また、引数に「category_name」を設定することによりカテゴリを絞ることもできます。

スポンサーリンク
レンタルサーバー
おすすめの記事