概要
elementor/frontend/the_content
アクションは、Elementorページビルダーで生成されたコンテンツに対してフックを提供します。このアクションは、WordPressがコンテンツを表示する際の最後の段階で呼び出される為、カスタムHTMLやJSコードを追加したり、ページの表示を変更したりする際によく使われます。このアクションを利用することで、Elementorを使用したサイトでのコンテンツの出力をカスタマイズし、特定の条件に基づいて追加情報を表示することができます。
具体的な使用例
- カスタムスクリプトの追加: ページコンテンツに特定のJavaScriptを埋め込む。
- 特定の条件下でのセクション追加: 記事の特定の地域で異なるコンテンツを表示。
- スタイルの適用: コンテンツに特定のCSSクラスを追加してスタイル変更。
- 条件付きロジック: ユーザーのログイン状態に基づいてコンテンツを表示。
- コンテンツのフィルタリング: 特定のショートコードを解釈して動的にコンテンツを挿入。
構文
add_action('elementor/frontend/the_content', 'your_function_name');
パラメータ
$content
(string): フィルタリングされたコンテンツを含む文字列。
戻り値
- 変更されたコンテンツが含まれる文字列。
使用可能なプラグインおよびWordPressのバージョン
- 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: カスタムスクリプトの追加
このコードは、ElementorのコンテンツにカスタムJavaScriptを追加します。特定のページでだけ実行されるように条件を設定しています。
add_action('elementor/frontend/the_content', 'add_custom_script_to_elementor_content');
function add_custom_script_to_elementor_content($content) {
if (is_page('special-page')) {
$content .= '<script>alert("This is a custom script!");</script>';
}
return $content;
}
引用元: https://developer.wordpress.org/plugins/hooks/
サンプル2: 特定の条件下でのセクション追加
このコードは、ログインしているユーザーにのみ特別なセクションを表示します。
add_action('elementor/frontend/the_content', 'add_section_for_logged_in_users');
function add_section_for_logged_in_users($content) {
if (is_user_logged_in()) {
$content .= '<div class="logged-in-section">Welcome back, friend!</div>';
}
return $content;
}
引用元: https://codex.wordpress.org/Plugin_API/Action_Reference
サンプル3: スタイルの適用
特定のコンテンツにCSSクラスを追加してスタイルを変更します。
add_action('elementor/frontend/the_content', 'add_custom_class_to_paragraphs');
function add_custom_class_to_paragraphs($content) {
return preg_replace('/<p>/', '<p class="custom-style">', $content);
}
引用元: https://www.smashingmagazine.com/2020/05/wordpress-custom-plugins/
サンプル4: コンテンツのフィルタリング
ショートコードを利用して動的にコンテンツを挿入します。
add_action('elementor/frontend/the_content', 'do_shortcode_in_elementor_content');
function do_shortcode_in_elementor_content($content) {
return $content . do_shortcode('[your_shortcode]');
}
引用元: https://www.wpbeginner.com/
サンプル5: 条件付きロジック
ユーザーの役割によって異なるメッセージを表示するサンプルです。
add_action('elementor/frontend/the_content', 'custom_message_based_on_user_role');
function custom_message_based_on_user_role($content) {
if (current_user_can('administrator')) {
$content .= '<div class="admin-message">Hello Admin!</div>';
}
return $content;
}
引用元: https://wordpress.stackexchange.com/questions/123174/how-to-use-the-current-user-role-in-a-function