WordPress
カスタマイズ事例

WORDPRESS CUSTOMIZATION

ショートコードに引数を持たせる

ショートコードに引数を持たせましょう。
例として、カスタム投稿タイプと取得する記事の件数を引数に持たせて、条件にあう記事を取得、表示する方法です。

テーマのfunctions.phpに以下を記述します。

if ( ! function_exists( 'display_result' ) ){
function display_result($atts) {
	global $post;
	extract(
		shortcode_atts(
			array(
				'result_post_type' => '',
				'result_post_num' => '-1'
			),
			$atts
		)
	);
	if($result_post_type!=''){
		$taxonomy_name = $result_post_type.'_cat';

		$the_query = new WP_Query( array(
			'post_status' => 'publish',
			'paged' => $paged,
			'posts_per_page' => $result_post_num, // 表示件数
			'tax_query' => array(
				array(
					'taxonomy' => $taxonomy_name,
					'field' => 'slug',
					'terms' => 'result',
				),
			),
		) );

	}

	if ($the_query->have_posts()) :

	endif;

	wp_reset_query();
}
add_shortcode('display_result', 'display_result');
}

これでショートコードはできました。
あとは、記事編集でショートコードを呼び出せば完了です。

display_result result_post_type="post_type_name" result_post_num="6"

(ショートコードなので[]で囲ってください)

【100ウェブ新着情報メルマガ】

WordPressカスタマイズ事例やウェブ制作ノウハウの新着情報、お役立ち情報を
リアルタイムにメルマガ配信!