概要説明
プラグインを使って管理することが多いですがfunctions.phpに記述を加えることでショートコードを追加することが可能です。PHPからもショートコードは利用可能です。広告用のコード、ウィジェット、何回も使う記述はショートコード管理がおすすめです。
~ 目次 ~
コード – 書式
function my_short_code_name() {
// 処理内容をこちらに記述
}
add_shortcode('任意のショートコード名', 'my_short_code_name');
[任意のショートコード名]
使用時は上記の書式で使用します
例 ) Google AdSense呼び出し用ショートコード
functions.php
/*----------------------------------------------------
ショートコード : アドセンス表示
----------------------------------------------------*/
function my_short_code_adsense() {
$code = <<< EOF
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=xxx" crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="xxx"
data-ad-slot="xxx"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
EOF;
echo $code;
}
add_shortcode('ad', 'my_short_code_adsense');
[ad] で使用可能
例 ) 投稿IDを渡してパーマリンクを表示
functions.php
/*----------------------------------------------------
ショートコード : パーマリンク取得 ( 引数 : id )
----------------------------------------------------*/
function my_short_code_get_permalink($atts) {
extract( shortcode_atts( array(
'id' => '',
), $atts ) );
return get_permalink( $atts['id'] );
}
add_shortcode('link', 'my_short_code_get_permalink');
[link id=投稿ID] で使用可能 // 結果 ) https://functions.fs-create.net/archives/92
例 ) パーマリンクを使用したaタグの取得
functions.php
/*----------------------------------------------------
ショートコード : タイトルリンクタグ取得 ( 引数 : id )
----------------------------------------------------*/
function my_short_code_get_post_link( $atts ) {
extract( shortcode_atts( array(
'id' => '',
), $atts ) );
return '<a href="'.get_permalink( $atts['id'] ).'">'.get_the_title( $atts['id'] ) . '</a>';
}
add_shortcode('linka', 'my_short_code_get_post_link');
[linka id=投稿ID] で使用可能 // 結果 )
PHPからショートコードを使用する場合
<?php echo do_shortcode('[ad]'); ?>
<?php echo do_shortcode('[link id="投稿ID"]'); ?>



