WordPressのWebサイト構築でよく使われる条件分岐タグをまとめてご紹介。
※「WordPress 条件分岐」と検索したときに検索ボリュームが多かったものを上から並べました
目次
複数条件の組み合わせ
AかつBのときに表示させたいものは以下のように、if文の中で&&
を用いて条件分岐させることができます。
コード
<?php if ( A && B ) : ?>
<?php endif; ?>
逆に、AまたはBのときに表示させたいものは以下のように、if文の中で||
を用いて条件分岐させることができます。
コード
<?php if ( A || B ) : ?>
<?php endif; ?>
▼▼▼
コード
<?php if ( is_page('news') || is_single() ) : ?>
<?php endif; ?>
カスタム投稿タイプの条件分岐
特定の投稿タイプで分岐
コード
<?php if(get_post_type() === '投稿タイプ名') : ?>
<?php endif; ?>
▼▼▼
コード
<?php if(get_post_type() === 'news') : ?>
<?php endif; ?>
特定のカスタム投稿アーカイブで分岐
コード
<?php if(is_post_type_archive('投稿タイプ名')) : ?>
<?php endif; ?>
▼▼▼
コード
<?php if(is_post_type_archive('news')) : ?>
<?php endif; ?>
特定のページテンプレートが使われている場合の条件分岐
コード
<?php if(is_page_template('page-company.php')) : ?>
<?php endif; ?>
カテゴリーの条件分岐
カテゴリー別記事一覧ページでの分岐
基本形
コード
<?php if(is_category()) : ?>
<?php endif; ?>
特定のカテゴリーを指定
コード
<?php if(is_category('カテゴリーID')) : ?>
<?php endif; ?>
記事詳細ページでの分岐
特定のカテゴリーを指定
コード
<?php if(in_category('カテゴリーID')) : ?>
<?php endif; ?>
複数指定
コード
<?php if(in_category(array('カテゴリーID','カテゴリーID'))) : ?>
<?php endif; ?>
ある条件以外での条件分岐
半角の!
を条件の前につけることで「〇〇以外のとき」を実現できます。
コード
<?php if(!is_front_page()) : ?>
<?php endif; ?>
トップページのときの条件分岐
コード
<?php if ( is_home() || is_front_page() ) : ?>
<?php endif; ?>
URLに含まれる文字列で条件分岐
コード
<?php
$url = $_SERVER['REQUEST_URI'];
if(strstr($url,'特定の文字列')==true):
?>
<?php endif; ?>
固定ページの条件分岐
基本形
コード
<?php if(is_page('固定ページのスラッグ') ) : ?>
<?php endif; ?>
複数指定
コード
<?php if(is_page(array(固定ページID,'固定ページスラッグ','ページタイトル'))) : ?>
<?php endif; ?>
検索結果ページの条件分岐
コード
<?php if(is_search()) : ?>
<?php endif; ?>
次はこの記事!






