Steamer Lane Studio技術備忘録ワードプレス

WordPress 非プラグイン single.phpにショートコードでファイル呼び出し

wordpress WordPress 非プラグイン single.phpにショートコードでファイル呼び出し
最終更新日: 2023年11月25日

表題の通り、投稿にショートコードでsingle.phpにファイルを読み込むためのコード。

function custom_php_include_shortcode($atts) {
if (isset($atts['file']) && file_exists($atts['file'])) {
ob_start();
include($atts['file']);
return ob_get_clean();
}
}
add_shortcode('custom_php_include', 'custom_php_include_shortcode');

上記コードをfunction.phpに記述。

[custom_php_include file="/path/to/your/file.php"]

上記(fileパスは適せん変更ね)をsingle.phpの任意の場所に挿入。
挿入先のコンテンツと挿入内容のhtmlなどに整合性が取れるよう注意。