WordPressのショートコードを使って、ちょっとした処理を出力したい時に。
ショートコードの基本形
add_shortcode()関数で処理する基本
function sample_func($atts, $content){
//実行したい処理
return 'Hello! World';
}
add_shortcode('sample', 'sample_func');
利用できるパラメータ
$atts - 属性の連想配列
$content - 囲み型のショートコードで使うコンテンツの内容
$tag - ショートコードのタグ
囲み型のショートコード
ショートコードタグを使ってタグで囲まれた部分を出力する
function sample_func($atts, $content){
return '<p class="today-word">'. $content .'</p>';
}
add_shortcode('sample', 'sample_func');
本文への記述
[sample]おはようございます[/sample]
出力
<p class="today-word">おはようございます</p>
属性と初期値を指定したショートコード
属性を利用して出力の幅を広げることができます。
function sample2_func($atts, $content){
$atts = shortcode_atts(array(
'link' => '/',
'text' => 'トップへ戻る'
), $atts);
extract($atts);
return '<div class="urlbtn"><a href="'. esc_url(home_url()). $link . '">' .$text. '</a></div>';
}
add_shortcode('sample2', 'sample2_func');
本文での記述、属性を指定しない場合は初期値で出力。例ではhome_urlを出力します。
[sample2]
<div class="urlbtn"><a href="https://tokushiyo.net/">トップへ戻る</a></div>
属性を追加する
[sample2 link="/web/post-1944/" text="MacでのPython開発環境の覚え書き、エラー対処"]
<div class="urlbtn"><a href="https://tokushiyo.net/web/post-1944">MacでのPython開発環境の覚え書き、エラー対処</a></div>
extract()は非推奨
WordPressのコーディング規約ではextract()を使うのは非推奨になっています。
Coding Standards Handbook
extract()
is a terrible function that makes code harder to debug and harder to understand. We should discourage it’s [sic] use and remove all of our uses of it.
extract()はコードのデバッグと解読を困難にするひどい関数。。。などと書いてありました。
extract()を使うと配列を変数として扱うことができるという便利なものですが便利であるが故に意図しないトラブルが起きやすいということでしょうか。
先程のコードをextract()を使わないと
function sample2_func($atts, $content){
$atts = shortcode_atts(array(
'link' => '/',
'text' => 'トップへ戻る'
), $atts);
return '<div class="urlbtn"><a href="'. esc_url(home_url()). $atts[link] . '">' .$atts[text]. '</a></div>';
}
add_shortcode('sample2', 'sample2_func');
特定のカテゴリの最新記事を表示する
カテゴリを指定して最新記事●件を表示させるショートコード
function disp_catpostlist_func($atts) {
$atts = shortcode_atts(array(
'cat_name' => '',
'count' => '',
),$atts
);
$args = array(
'category_name' => $atts['cat_name'],
'posts_per_page' => $atts['count'],
'post_status' => 'publish',
'orderby' => 'desc'
);
$the_query = new WP_Query($args);
$html = '';
if($the_query->have_posts()):
$html = '<ul class="catpost">';
while($the_query->have_posts()):
$the_query->the_post();
$html .= '<li>
<a href="' . get_permalink( $post->ID ) . '" >'
. get_the_title( $post->ID ) . '</a>
</li>';
endwhile;
wp_reset_postdata();
$html .= '</ul>';
endif;
return $html;
}
add_shortcode( 'disp_catpostlist', 'disp_catpostlist_func' );
ブロックエディタが段々と進化してきてわざわざコードを書かなくてもできることが多くなりましたがショートコードを使って表示を制御する場面はまだまだ多いです。
ショートコードが簡単に登録管理できるWordPressプラグイン Shortcorder
定型文や広告タグを手軽に管理したいなら「Shortcorder」というプラグインが便利です。
https://ja.wordpress.org/plugins/shortcoder/
- ブロックエディタにも対応しているので投稿画面で簡単に呼び出して挿入可能
- PHPは挿入できませんがJavascriptは可能
- WordPress変数、カスタムパラメータ、カスタムフィールドも利用可能