概要
elementor/page_templates/header-footer/before_content
は、Elementorプラグインで提供されるフックの一つです。これにより、ページテンプレートのコンテンツが表示される前に特定のカスタムコードや処理を追加することができます。このアクションは、特に以下の6つの機能を実装する際によく使われます。
- カスタムメタデータの表示
- トラッキングコードの埋め込み
- 広告やバナーの追加
- コンテンツの条件付き表示
- レイアウトのカスタマイズ
- 外部APIからのデータフェッチング
構文
do_action('elementor/page_templates/header-footer/before_content');
パラメータ
このアクションには特にパラメータはありませんが、実行時にWordPressの全てのグローバル変数を利用することができます。
戻り値
このアクションは何も戻しません。
使用可能なバージョン
- Elementor: バージョン3.0以上
- WordPress: バージョン5.0以上
サンプルコード
サンプル1:カスタムメッセージを表示
このサンプルコードは、特定のページでカスタムメッセージを表示します。
add_action('elementor/page_templates/header-footer/before_content', function() {
if ( is_page('contact') ) {
echo '<div class="custom-message">ご意見ご感想をお聞かせください!</div>';
}
});
- このコードは、’contact’ページが開かれた際にカスタムメッセージを表示します。
引用元
- https://developer.wordpress.org/reference/functions/add_action/
サンプル2:トラッキングコードの追加
このコードは、Google Analyticsのトラッキングコードを特定のページに追加します。
add_action('elementor/page_templates/header-footer/before_content', function() {
echo "<script async src='https://www.googletagmanager.com/gtag/js?id=UA-XXXXX-Y'></script>";
echo "<script>window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXX-Y');</script>";
});
- Google Analyticsのトラッキングコードを埋め込みます。
引用元
- https://www.analyticsmania.com/post/add-google-analytics-in-wordpress/
サンプル3:特定ユーザーのみのコンテンツ表示
このコードは、特定のユーザーだけに特別なコンテンツを表示します。
add_action('elementor/page_templates/header-footer/before_content', function() {
if ( current_user_can('subscriber') ) {
echo '<div class="subscriber-content">購読者限定コンテンツ</div>';
}
});
- 購読者(subscriber)のみがアクセスできるコンテンツを表示します。
引用元
- https://developer.wordpress.org/reference/functions/current_user_can/
サンプル4:オンラインストアバナーの追加
このコードは、ページの最上部にオンラインストアのバナーを追加します。
add_action('elementor/page_templates/header-footer/before_content', function() {
echo '<div class="banner">🌟 セール中!全品20%オフ! 🌟</div>';
});
- セール情報を含むバナーを表示します。
引用元
- https://www.wpbeginner.com/wp-tutorials/how-to-add-custom-banner-message-in-wordpress/
サンプル5:外部APIからのデータ取得
このコードは、外部APIからのデータを取得し表示します。
add_action('elementor/page_templates/header-footer/before_content', function() {
$response = wp_remote_get('https://api.example.com/data');
if ( is_array($response) && ! is_wp_error($response) ) {
$data = json_decode($response['body'], true);
echo '<div class="api-data">' . esc_html($data['important_info']) . '</div>';
}
});
- 外部APIからデータを取得し、その情報を表示します。
引用元
- https://developer.wordpress.org/reference/functions/wp_remote_get/
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |