wp_register_styleと
wp_enqueue_style仕組み:
wp_register_styleは、あなたがあなた自身のスタイルシートを登録し、それらを自分のハンドルを与えることができます。これにより、すべてのスタイルを定義し、必要に応じてロードすることができます。多くの場合、スタイルシートはテーマのライフサイクルの早い段階で登録されていることがよくあります。その後、いくつかの論理チェックに基づいてエンキューされます。一例として、
:
あなたはいくつかのカスタムショートを持っていますが、ショート自身が実際に使用されない限り、そのスタイルシートのいずれかをロードしたくないとしましょう:
のfunctions.php
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
//Register the style
wp_register_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}
add_action('init', 'custom_init');
function custom_init()
{
//Example shortcode
add_shortcode('my_shortcode', 'custom_shortcode');
}
function custom_shortcode($atts, $content = null)
{
//If registered style isn't loaded....
if (!wp_style_is('my-shortcode-styles')) {
//Enqueue it!
wp_enqueue_style('my-shortcode-styles');
}
return 'My Shortcode!';
}
ほとんどの場合でも、wp_enqueue_styleで十分です。これを使用して、あなたはすべてを一度あなたのスタイルシートを登録し、エンキューすることができますあなたの場合は
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
//Register and enqueue the style
wp_enqueue_style('my-shortcode-styles', get_template_directory_uri() . '/css/shortcode-styles.css');
}
を、ユーザーが適切なスタイルシートをロードする前に訪問されるページを決定するためにいくつかの簡単な論理チェックを実行することができます。
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');
function custom_enqueue_scripts()
{
if(is_home()){ //is_front_page() if you're using a Page for the home page
//Load only on the home page
wp_enqueue_style('home-styles', get_template_directory_uri() . '/css/styles1.css');
}
//Load everywhere else
wp_enqueue_style('my-theme', get_template_directory_uri() . '/css/styles2.css');
}
クイックノート:スタイルシートのエンキューが動作するためには、あなたのテーマMUST使用wp_headとwp_footer。アクティブなテーマでテンプレートファイルが見つからない場合、スタイルシートエンキューは動作しません。
参照:
私はあなたが 'is_home(持って、この文の中に、IF-THEN文を持っていることを確認)'その機能を--is front-page.phpを取得しますか?また、 'home-styles'と' my-theme'はランダムなラベルか、WordPressやテーマの中で何かを参照していますか? – Matt
'is_home()'はあなたがホームページを見ているかどうかを判断するWordpress関数です。 'home-styles'と' my-theme'は単なるランダムなラベルです。あなたは好きなものに変更することができますが、 'wp_register_style'と' wp_enqueue_style'の組み合わせを使用している場合、それらのハンドルは同じである必要があります。 – maiorano84
詳細な対応をありがとうございます。これらの2つの関数is_home()とis_front_page()はトリックでした! – Matt