概要
elementor/template-library/get_template
関数は、Elementorプラグインの中でテンプレートを取得するための非常に重要なフックです。この関数は、Elementorのテンプレートライブラリから特定のテンプレートを取得し、表示するために頻繁に使用されます。具体的には、以下のような機能を実装する際によく使用されます。
- テンプレートのカスタマイズ
- 特定のページ向けのプリビルトテンプレートの読み込み
- テーマやプラグインの統合
- カスタムデザインの適用
- ウィジェットやショートコードとの連携
- テンプレートの動的な切り替え
構文
elementor/template-library/get_template( $template_id, $args = array() );
パラメータ
$template_id
(string): 取得したいテンプレートのID。$args
(array, optional): 追加の引数(デフォルトは空の配列)。
戻り値
- 取得したテンプレートのHTMLコンテンツまたはfalse。
プラグインおよびワードプレスのバージョン
- Elementorバージョン: 3.0以上
- WordPressバージョン: 5.0以上
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプル1: 特定のテンプレートを取得して表示
$template_id = '1234'; // 取得したいテンプレートのID
$template_html = ElementorPlugin::instance()->templates_manager->get_template( $template_id );
if ( $template_html ) {
echo $template_html; // テンプレートを表示
}
このコードは、特定のIDを持つテンプレートを取得し、存在する場合はそのHTMLを出力します。
サンプル2: 引数を指定してテンプレートを取得
$template_args = array(
'content' => 'Hello World!'
);
$template_id = '5678'; // 取得したいテンプレートのID
$template_html = ElementorPlugin::instance()->templates_manager->get_template( $template_id, $template_args );
if ( $template_html ) {
echo $template_html; // テンプレートを表示
}
このコードは、特定の引数を渡してテンプレートを取得する方法を示しています。
サンプル3: ウィジェット内でテンプレートを利用
class My_Custom_Widget extends ElementorWidget_Base {
public function render() {
$template_id = '91011'; // ウィジェットで使用するテンプレートID
$template_html = ElementorPlugin::instance()->templates_manager->get_template( $template_id );
echo $template_html; // テンプレートを表示
}
}
このクラスは、カスタムウィジェット内でテンプレートを取得して表示する方法を示しています。
サンプル4: Ajaxリクエストでテンプレートを取得
add_action('wp_ajax_get_template', 'get_template_callback');
function get_template_callback() {
$template_id = intval($_POST['template_id']);
$template_html = ElementorPlugin::instance()->templates_manager->get_template( $template_id );
if ($template_html) {
echo $template_html; // テンプレートを表示
}
wp_die();
}
Ajaxリクエストを受け取り、指定されたテンプレートを取得して表示するサンプルコードです。
サンプル5: ショートコードでテンプレートを利用
function template_shortcode( $atts ) {
$atts = shortcode_atts( array(
'id' => '1234',
), $atts );
$template_html = ElementorPlugin::instance()->templates_manager->get_template( $atts['id'] );
return $template_html ? $template_html : '';
}
add_shortcode( 'elementor_template', 'template_shortcode' );
このショートコードを使って、指定されたIDのテンプレートを簡単に表示できるようにするサンプルです。