0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

functions.phpの中でis_front_page()やis_home()を使いたい時の書き方

Last updated at Posted at 2021-09-10

テンプレートファイルの中なら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' );

上記のような処理になっています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?