プラグインElementorのelementor/frontend/before_enqueue_stylesアクションの使用方法・解説

概要

elementor/frontend/before_enqueue_stylesは、Elementorのフックであり、スタイルシートがキューに追加される前にカスタムスタイルを追加するために使用されます。このアクションは、特定の条件に基づいてカスタムスタイルを動的に追加する際によく利用されます。よく使われる機能としては、以下のようなものがあります。

  1. 条件付きスタイルの追加: ページや投稿の種類に基づいて異なるスタイルを適用。
  2. カスタムCSSの追加: 特定の条件を満たす場合にのみ、カスタムCSSを追加。
  3. 外部スタイルシートのインポート: 特定の条件下で外部のスタイルシートをインポートする。
  4. スタイルの最適化: 開発環境と本番環境で異なるスタイルを読み込む。
  5. スクリプトの連動: JavaScriptによる動的効果に対応したスタイルの追加。
  6. テーマのカスタマイズ: 使用しているテーマに合わせたスタイルの変更。

構文

add_action('elementor/frontend/before_enqueue_styles', 'your_custom_function');

パラメータ

このアクションは特定の引数を取らないため、コールバック関数内でグローバル変数やその他の方法を使用してデータを取得する必要があります。

戻り値

このアクションは何も戻さず、主にスタイルシートをキューに追加するための機能を実行します。

おすすめバージョン

  • Elementor: 2.0以上
  • WordPress: 4.0以上

サンプルコード

サンプルコード1

add_action('elementor/frontend/before_enqueue_styles', function() {
    if ( is_single() && 'post' === get_post_type() ) {
        wp_enqueue_style('custom-post-style', get_template_directory_uri() . '/css/custom-post.css');
    }
});

このコードは、投稿ページが表示されている場合にのみ、特定のスタイルシートをキューに追加します。

サンプルコード2

add_action('elementor/frontend/before_enqueue_styles', function() {
    if (is_page('contact')) {
        wp_enqueue_style('contact-style', get_template_directory_uri() . '/css/contact.css');
    }
});

このサンプルは、「contact」というスラッグのページが表示されている場合にのみ、連動するスタイルを追加します。

サンプルコード3

add_action('elementor/frontend/before_enqueue_styles', function() {
    if ( is_user_logged_in() ) {
        wp_enqueue_style('logged-in-style', get_template_directory_uri() . '/css/logged-in.css');
    }
});

この例では、ユーザーがログインしている場合に限り、特定のスタイルを読み込むことができます。

サンプルコード4

add_action('elementor/frontend/before_enqueue_styles', function() {
    $current_hour = date('G');
    if ($current_hour < 12) {
        wp_enqueue_style('morning-style', get_template_directory_uri() . '/css/morning.css');
    } else {
        wp_enqueue_style('evening-style', get_template_directory_uri() . '/css/evening.css');
    }
});

ここでは、時間帯に基づいて異なるスタイルシートを読み込むサンプルです。

サンプルコード5

add_action('elementor/frontend/before_enqueue_styles', function() {
    if (is_product_category('special')) {
        wp_enqueue_style('special-category-style', get_template_directory_uri() . '/css/special-category.css');
    }
});

このコードは、特定の製品カテゴリーのアーカイブが表示されるときに、専用のスタイルを追加します。

この関数のアクションでの使用可能性

アクション 使用可能性
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

以上がelementor/frontend/before_enqueue_stylesの解説とサンプルコード、アクションの使用可能性の詳細です。

この関数について質問する


上の計算式の答えを入力してください