wordpress phpファイルをショートコード化 2016年5月8日
Tag:
phpファイルをショートコード化して表示します。
1.まずinclude用でテンプレートを作成します。
例:include-blog.php
2.functions.phpに下記を追加します。
//PHPファイルをショートコードから読み込む
function my_include_php($atts) {
$attrs = shortcode_atts($atts);
$file = $attrs["file"];
if (!empty($file) && preg_match('/^[0-9a-zA-Z\-\_]+$/', $file)) {
$file = dirname(__FILE__)."/include-".$file.".php";
if (is_file($file)) {
ob_start();
include $file;
$s = ob_get_contents();
ob_end_clean();
return $s;
}
}
return "";
}
add_shortcode('my_include_php', 'my_include_php');
2.エディタ内で表示させる場合は
[my_include_php file="blog"] //blogは作成したテンプレート名
3.テンプレート内で表示させる場合は
<?php echo do_shortcode('[ショートコード文字列] ');?>
//またはショートコードを使わずincludeさせる
<?php get_template_part( 'include', 'blog' ); ?>