[WordPress] 指定ページヘッダサイドバー表示切り替える方法

4 min read
hiroweb developer

やりたいこと

  • 404 ページの時にヘッダーとサイドバーを表示しない
  • 条件は条件分岐タグを使いたい

実装

前提

基本的にサイドバーなどのテンプレートはは以下のように呼ぶ。

get_template_part('templates/common/sidebar');

これをラップする。

呼び出し

get_template_part()の代わりにこんな感じで呼び出す。

Template::get_template_header();

内部の実装は以下のような感じ。

public static function get_template_header() {
  if ( self::is_display_header() ) {
    get_template_part('templates/common/header');
  }
}

判定

private static $header_invisible  = ['is_404'];
private static $sidebar_invisible = ['is_404'];

public static function is_display_header() {
  return self::is_display(self::\$header_invisible);
}

$header_invisible$sidebar_invisibleは、配列で WordPress の条件分岐タグを文字列で入れていく。以下の様な感じ。

private static $header_invisible = ['is_home', 'is_single', 'is_404'];

ページの条件分岐を判定する

is_display()の引数には条件分岐タグを入れた配列を指定する。

private static function is_display($invisible) {
  $display = true;
  // 指定の条件分岐に該当するものがある場合は非表示にする
  if (in_array(true, self::set_conditional_result_from_str($invisible) ) ) {
      $display = false;
  }

  return $display;
}

指定のページ(条件分岐タグ)が指定されていたら、この場合ヘッダを非表示にする(\$displayfalse)。

private static function set_conditional_result_from_str($funcs) {
  $result = [];

  foreach($funcs as $is_conditional) {
    if( function_exists($is_conditional) ) {
      $result[] = $is_conditional(); // true or false
    } else {
      $result[] = false;
    }
  }

  return $result;
}

条件分岐タグの文字列("is_home"など)をfunction_exists()で存在チェックをし、存在する場合は関数として実行する。
条件分岐タグが存在していれば、条件分岐タグから返される判定を$resultに入れる。そもそも指定の関数が存在しなければfalse$resultに入れる。

完成

<?php

class Template {
  private static $header_invisible  = ['is_404'];
  private static $sidebar_invisible = ['is_404'];


  public static function get_template_header() {
    if ( self::is_display_header() ) {
      get_template_part('templates/common/header');
    }
  }

  public static function get_template_sidebar() {
    if ( self::is_display_sidebar() ) {
      get_template_part('templates/common/sidebar');
    }
  }

  public static function get_template_footer() {
    get_template_part('templates/common/footer');
  }


  public static function is_display_header() {
    return self::is_display(self::$header_invisible);
  }

  public static function is_display_sidebar() {
    return self::is_display(self::$sidebar_invisible);
  }

  private static function is_display($invisible) {
    $display = true;
    // 指定の条件分岐に該当するものがある場合は非表示にする
    if (in_array(true, self::set_conditional_result_from_str($invisible) ) ) {
      $display = false;
    }
    return $display;
  }

  // 文字列から条件分岐タグの結果を取得する
  private static function set_conditional_result_from_str($funcs) {
    $result = [];
    foreach($funcs as $is_conditional) {
      if( function_exists($is_conditional) ) {
          $result[] = $is_conditional(); // true or false
      } else {
          $result[] = false;
      }
    }
    return $result;
  }
}