私はWordPress開発にはかなり新しいです。私はwp_enqueue_style
とdo_action
をfunctions.php
ファイルの中に使用する方が、WordPressを使用しないときと同じようにCSSファイルを直接リンクするよりも良いことを読んだ。WordPressのリンクタグよりもwp_enqueue_styleを使用する方が良いのはなぜですか?
なぜこれがベストプラクティスですか?その利点は何ですか?
私はWordPress開発にはかなり新しいです。私はwp_enqueue_style
とdo_action
をfunctions.php
ファイルの中に使用する方が、WordPressを使用しないときと同じようにCSSファイルを直接リンクするよりも良いことを読んだ。WordPressのリンクタグよりもwp_enqueue_styleを使用する方が良いのはなぜですか?
なぜこれがベストプラクティスですか?その利点は何ですか?
子テーマを有効にしている場合は、get_template_directory_uri()
機能を使用してください。
親テーマを有効にしている場合は、get_stylesheet_directory_uri()
機能を使用してください。
get_template_directory_uriは常にアセットの親テーマフォルダを参照します。
get_stylesheet_directory_uriは、アセットの「現在の」テーマフォルダ(呼び出された場所に応じて親または子になる可能性があります)を参照します。
子テーマ例:
wp_enqueue_style('my_child_styles', get_stylesheet_directory_uri().'/style.css');
親テーマ例
wp_enqueue_style('my_parent_styles', get_template_directory_uri().'/style.css');
方法-1
// load css into the website's front-end
function mytheme_enqueue_style() {
wp_enqueue_style('mytheme-style', get_stylesheet_directory_uri().'/style.css');
}
add_action('wp_enqueue_scripts', 'mytheme_enqueue_style');
方法-2
// Add this code in your functions.php
function add_stylesheet_to_head() {
echo "<link href='".get_stylesheet_directory_uri()."/style.css' rel='stylesheet' type='text/css'>";
}
add_action('wp_head', 'add_stylesheet_to_head');
WP-エンキュースタイルは、キューにスクリプト/スタイルを追加しますので。
ソースが提供されていて(上書きしないで)エンキューする場合は、スタイルを登録します。
答えていただきありがとうございますが、なぜ私はwp_enqueue_styleとadd_actionを使用して、ヘッダーにリンクタグを追加してCSSファイルをリンクすることができるのかという疑問がありました。なぜ最初の方法が良いですか? –
@KareemAbdelwahed他のプラグインが同じCSSファイルを使用している場合、CSSファイルが既にページに含まれているかどうかを確認することはできません。その後、プラグインは同じファイルを2回目に読み込み、重複したコードを生成します。 --- 幸いにも、WordPressには、スタイルシートの登録とエンキューのような問題に対する非常に簡単な解決策があります。 – purvik7373