2021.12.08WEB - WordPress

WordPressでショートコードを使う

制作会社や納期、予算によって、WPのエディタにがっつりhtml書き込むこともあるかと思います。
その中で、ホームのURLやお知らせなどの投稿一覧を表示させたい時は、ショートコード管理が便利です。

ショートコード管理をするにはadd_shortcodeを使用します。
例)

function sc_tcr() {
	return 'ところてん';
}
add_shortcode('tcr', 'sc_tcr');

→[tcr]で「ところてん」表示

ホームURL

functions.phpに

function sc_homeurl() {
	return esc_url(homeurl('/'));
}
add_shortcode('homeurl', 'sc_homeurl');

エディタに

[homeurl]

でホームURL表示

テンプレートURL

functions.phpに

function sc_tmp() {
	return esc_url(get_template_directory_uri());
}
add_shortcode('tmp', 'sc_tmp');

エディタに

[tmp]

でテンプレートURL表示

投稿一覧

functions.phpに

function shortcode_post_list($atts) {
	extract(shortcode_atts(array( //引数の値を取得
		'num' => '3', //表示件数。ショートコード側で指定がなければここで設定した値になる。
		'post_type' => 'post' //投稿タイプ。ショートコード側で指定がなければここで設定した値になる。
	), $atts));
	global $post;
	$args = array(
		'posts_per_page' => $num, //表示件数
		'post_type'      => $post_type, //投稿タイプ
		'post_status'    => 'publish' //投稿ステータス
	);
	$posts_array = get_posts($args);
	$list = ''; //変数セット
	foreach($posts_array as $post):
		setup_postdata($post);
		//ループで表示したいものをここへ
		$list .= '<li>';
		$list .= '<span class="date">'.get_the_time('Y/m/d').'</span><span class="ttl"><a href="'.get_permalink().'">'.get_the_title().'</a></span>';
		$list .= '</li>';
	endforeach;
	wp_reset_postdata();
	return $list;
}
add_shortcode('post_list', 'shortcode_post_list');

エディタの埋め込みたい箇所へ

[post_list num="3" post_type="post"]

表示させる数とポストタイプは任意で。

参考:WordPress ショートコードを使った投稿一覧の表示方法