LoginSignup
43
51

More than 5 years have passed since last update.

[WordPress] 固定ページの子ページかどうか条件分岐させる方法

Last updated at Posted at 2014-12-11

色んな条件分岐タグがあるWordPressですが子ページかどうか調べるis_subpage()のような条件分岐タグはありません。毎回調べるのでメモしておきます。

固定ページの子ページかどうか判定

if (is_page() && $post->post_parent) {
    // 子ページ
} else {
    // 子ページではない
}

上記の判定を is_subpage() と関数で使う場合

functions.php
function is_subpage() {
  global $post;
  if (is_page() && $post->post_parent){
    $parentID = $post->post_parent;
    return $parentID;
  } else {
    return false;
  };
};

これで判定させたい場所で is_subpage()を使えます。

親ページと子ページもtrueにさせたい場合

IDで指定するならそのまま。

if ( is_page(1234) || $post->post_parent === 1234 ) {
    // 親ページと子ページ
}

これでも可能ですがローカル環境とテスト環境、さらに本番環境が同じIDである事はまずないので、
スラッグで分岐させるのが楽です。

固定ページの親ページと子ページをスラッグで判定する方法

まずfunctions.phpに下記の関数を作って、

functions.php
function is_parent_slug() {
  global $post;
  if ($post->post_parent) {
    $post_data = get_post($post->post_parent);
    return $post_data->post_name;
  }
}

判定させたい場所で上記関数を使って判定出来ます。

if (is_page('hoge') || is_parent_slug() === 'hoge') {
  // スラッグが hoge ならtrue
}
43
51
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
43
51