Skip to content

Instantly share code, notes, and snippets.

@ksk1015
Created October 23, 2018 10:42
Show Gist options
  • Save ksk1015/0a3e049615cf60991fd7f97524f1e21e to your computer and use it in GitHub Desktop.
Save ksk1015/0a3e049615cf60991fd7f97524f1e21e to your computer and use it in GitHub Desktop.
wordpress ショートコードをファイルで管理しやすくするための、ファイルのパスを引数にショートコードを生成する関数
function add_shortcode_template ($name, $template = '') {
if ( !$template ) {
$template = $name;
$name = basename($template, '.php');
}
if ( !preg_match('/\.php$/', $template) ) {
$template .= '.php';
}
$template = get_template_directory() . '/' . $template;
add_shortcode($name, function ($atts, $content = '') use ($template) {
ob_start();
include $template;
return ob_get_clean();
});
}
function add_shortcode_template_dir ($dir) {
if ( !preg_match('/\/$/', $dir) ) {
$dir .= '/';
}
$dir_path = get_theme_file_path($dir);
foreach (scandir($dir_path) as $file_name) {
if ( preg_match('/\.php$/', $file_name) ) {
add_shortcode_template($dir . $file_name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment