wp_enqueue_styleをfunctions.phpに素で書くとエラーが出るのを回避

TwentyTwelveテーマの子テーマを作る場面に出会いました。ウェブルジョンさんの下記の記事を参考に、functions.phpに下記を書き込んだところ、エラーが出てしまいました。

参考にした記事

Twenty Twelveの子テーマをつくるときに wp_enqueue_style を使ったほうが幸せになれるかもしれないという話 | Webourgeon

書いたコード

<br />
if ( !is_admin() ) {<br />
	wp_enqueue_style( 'twentytwelve-style', get_template_directory_uri() . '/style.css', array(), date('YmdHis', filemtime(get_template_directory() . '/style.css')) );<br />
	wp_enqueue_style( 'twentytwelve-child-style', get_stylesheet_uri(), array('twentytwelve-style'), date('YmdHis', filemtime(get_stylesheet_directory() . '/style.css')) );<br />
	wp_enqueue_style( 'twentytwelve-ie', get_template_directory_uri() . '/css/ie.css', array(), date('YmdHis', filemtime(get_template_directory() . '/css/ie.css')) );<br />
	$wp_styles->add_data( 'twentytwelve-ie', 'conditional', 'lt IE 9' );<br />
}<br />

出たエラー

Notice: wp_enqueue_style が誤って呼び出されました。スクリプトおよびスタイルは wp_enqueue_scripts、admin_enqueue_scripts、init フック以降のみに登録・キュー追加できます。 詳細は WordPress のデバッグをご覧ください。 (このメッセージはバージョン 3.3 で追加されました) in /var/www/vhosts/hiheyhoi/wp-includes/functions.php on line 2959

何かフックしてくれという感じですので、関数にして、一番最初の wp_enqueue_scripts フックに登録したところ、エラーは表示されなくなりました。

wp_enqueue_scriptsによれば、フロントエンドでのスタイルのためにこのフックを使いましょう(wp_enqueue_scripts is the proper hook to use when enqueuing items that are meant to appear on the front end.)ということで、if(!is_admin()){}が取れました。また、 global $wp_styles; の追加が必要でした。

最終的にfunctions.phpに追記したもの

<br />
function add_child_styles()<br />
{<br />
	global $wp_styles;<br />
	wp_enqueue_style( 'twentytwelve-style', get_template_directory_uri() . '/style.css', array(), date('YmdHis', filemtime(get_template_directory() . '/style.css')) );<br />
	wp_enqueue_style( 'twentytwelve-child-style', get_stylesheet_uri(), array('twentytwelve-style'), date('YmdHis', filemtime(get_stylesheet_directory() . '/style.css')) );<br />
	wp_enqueue_style( 'twentytwelve-ie', get_template_directory_uri() . '/css/ie.css', array(), date('YmdHis', filemtime(get_template_directory() . '/css/ie.css')) );<br />
	$wp_styles->add_data( 'twentytwelve-ie', 'conditional', 'lt IE 9' );<br />
}<br />
add_action( 'wp_enqueue_scripts', 'add_child_styles' );<br />

目次

感想

WordPress/wp-includes/script-loader.php at 3.5.1 · WordPress/WordPress · GitHubを見ると、

function wp_enqueue_scripts() {
	do_action('wp_enqueue_scripts');
}

となっており、WRAPしているだけ。その直前のコメントには、

* Allows plugins to queue scripts for the front end using wp_enqueue_script().
* Runs first in wp_head() where all is_home(), is_page(), etc. functions are available.

とあるので、is_home()などの条件分岐タグを使いたいときには、initアクションフックではなく、こちらの方がいいですよ、そのために、do_actionするだけの関数も作りましたよ、ということなのかな、と思いました。間違ってるかもですが・・・

WordPressの実行フローを視覚化してみる | Simple Colors

この記事が気に入ったら
フォローしてね!

よかったらシェアしてね!

著者について

コメント

コメント一覧 (1件)

コメントする

目次
閉じる