条件式
sample.php
// A and B
&&
// A or B
||
// not
!
指定
sample.php
// ホームページ
is_home
// フロントページ
is_front_page()
// 投稿ページ
is_single()
// 固定ページ
is_page()
// カテゴリー
in_category()
// スマホのみ表示
wp_is_mobile())
記事指定
sample.php
// 記事単数
if(is_single('1'))
// 記事複数
if(is_single(array(1, 2, 3, 4)))
// 1でない全ての投稿ページ
if(! is_single('1'))
取得
カテゴリー名
sample.php
// リンク付き
<?php the_category(); ?>
// リンクなし
<?php $cat = get_the_category(); $cat = $cat[0]; { echo $cat->cat_name; } ?>
条件分岐
すべての投稿ページ、もしくは固定ページA,Bで表示する
sample.php
<?php if(is_single() || is_paged(array('A','B')) ): ?>
投稿ページ、もしくは固定ページA,Bで表示する
<?php else: ?>
それ以外で表示する
<?php endif; ?>
スマホでA、PCでBを表示する
sample.php
<?php if(wp_is_mobile()): ?>
A
<?php else: ?>
B
<?php endif; ?>
カスタムフィールド
カスタムフィールド(フィールド名:cf-lead)を取得
sample.php
<?php $imgid = get_field('cf-lead'); ?>
<?php if (empty($imgid)): ?>
<?php else: ?>
<div><?php the_field('cf-lead'); ?></div>
<?php endif; ?>
応用
スラッグで子ページが親ページを判断できるようにする
wordpressにおいて、ページについては一律で子ページ扱いになり、所属している親に対しての条件分岐は標準ではできません。
以下のように記述することで、分岐できるようになります。
function.php
function is_parent_slug() {
global $post;
if ($post->post_parent) {
$post_data = get_post($post->post_parent);
return $post_data->post_name;
}
}
sample.php
<?php if (is_page('hoge') || is_parent_slug() === 'hoge') { ?>
スラッグが hoge ならtrue
<?php } ?>