ショートコードの作成方法を見ていきたいと思います。
投稿や固定ページの中で少々phpを使用した内容をを出力したい場合や、ある程度決まった方で出力する場合に便利です。
ショートコードには2種類あり
ショートコードのみで出力を行う方法
ショートコードで囲った内容にアプローチする方法
です。
どちらのタイプの作成方法も見てみたいと思います。
ショートコードのみで出力を行う方法
まず、ショートコードのみで出力を行うタイプのものです。
[same_category_post num="3"]
現在の投稿とカテゴリーが同じ投稿を3つリストで返すものとします。
上の通りショートコード名と引数を指定しています。
これらを使用できるよう「add_shortcode」で定義します。
add_shortcode( 'same_category_post', function( $atts ) {
$atts = shortcode_atts( [
'num' => 5
], $atts );
global $post;
$categories = get_the_category( $post->ID );
$cat_id = [];
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
}
$args = [
'post_type' => 'post',
'category__in' => $cat_id,
'post__not_in' => [ $post->ID ],
'posts_per_page' => $atts['num']
];
ob_start();
$query = new WP_Query( $args );
echo '<ul>';
if( $query->have_posts() ) :
while( $query->have_posts() ) :
$query->the_post();
?>
<li><a href="<?php echo get_the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
endif;
wp_reset_postdata();
return ob_get_clean();
} );
「add_shortcode」に指定する関数では引数を3つとります。
「$atts」・・・ショートコードの引数の配列。
「$content」・・・ショートコードで囲った場合の囲った内容(次で使用します)。
「$shorcode_name」・・ショートコードの名前。
$attsで予期しない引数が指定されないように「shortcode_atts」によって引数を調整しています。
shortcode_attsの引数の一つ目は「調整するための配列」を指定します。
仮に引数が指定されなくてもshortcode_attsの第一引数で指定した値が指定されます。
また、予期しない値が引数が指定された場合でもshortcode_attsのキーにない場合除外することができます。
第2引数は第一引数を上書きする値です。
[same_category_post post_type="foo" num="3"]
//上のコードでショートコードが呼ばれた場合
add_shortcode( 'same_category_post', function( $atts ) {
$atts = shortcode_atts( [
'num' => 5
], $atts );
//$attsは
$atts = [
'num' => 3
];
ショートコードで囲った内容にアプローチする方法
次にショートコードで囲った内容にアプローチする方法です。
ここでは簡単にショートコードで囲われた内容にマーカー用の「span」タグを付与するものとします。
[marker color="#123456"]マーカーで線をひきます[/marker]
ショートコード側は以下のようになります。
add_shortcode( 'marker', function ( $atts, $content ) {
$atts = shortcode_atts( [
'color' => '#333'
], $atts );
$span_css = '<span style="background: linear-gradient(transparent 60%,'. $atts['color']. ' 60%)">';
returnn $span_css. $content. '</span>';
} );
先ほど同様にショートコードの整理を行っています。
ショートコードで囲まれた内容を<span>で囲い、指定されたカラースタイルを付与しています。
さいごに
これでショートコードの仕様ができると思います。
ショートコードでは文字列を返すようにしましょう。
ob_startなど使わずそのまま出力してしまうと、予期しない場所にショートコードの内容が出力されてしまいます。