テンプレートファイルの中ならis_front_page()が正しく動作するのにfunctions.phpの中に書くと常にfalseしか返ってこない。
if(is_front_page()) {
// トップページのみの処理
}
つまり上記のように書いて動作しない。たぶんフックを使ってないからです。
解決方法
選ぶフックは、functions.phpが読み込まれた直後の after_setup_theme
でよさそうです。
add_action('after_setup_theme', function() {
if(is_front_page()) {
// トップページのみの処理
}
});
上記のように書きます。
add_action('wp', function() {
if(is_front_page()) {
// トップページのみの処理
}
});
覚えやすい wp
とかでもいいと思います。なんでもいいので、とにかくフックに紐付けます。
解説
functions.phpでカスタマイズを加える場合、基本的にフックを使うべきです。functions.phpが読み込まれるタイミングではページ情報の判定はできません。フックに登録した処理が呼び出される時点でないとページ情報の判定はできません。
functions.phpが読み込まれるのは上記のタイミング。
// Load the functions for the active theme, for both parent and child theme if applicable.
foreach ( wp_get_active_and_valid_themes() as $theme ) {
if ( file_exists( $theme . '/functions.php' ) ) {
include $theme . '/functions.php';
}
}
unset( $theme );
/**
* Fires after the theme is loaded.
*
* @since 3.0.0
*/
do_action( 'after_setup_theme' );
上記のような処理になっています。