WordPressのfunction.phpで常用するコード③(ループ編)
2016.07.05
loop何番目か
function.php
// loop最初 function isFirst(){ global $wp_query; return ($wp_query->current_post === 0); } // loop最後 function isLast(){ global $wp_query; return ($wp_query->current_post+1 === $wp_query->post_count); } // loop偶数 function isOdd(){ global $wp_query; return ((($wp_query->current_post+1) % 2) === 1); } // loop奇数 function isEver(){ global $wp_query; return ((($wp_query->current_post+1) % 2) === 0); } // loop3つめ function is3rd(){ global $wp_query; return ((($wp_query->current_post+1) % 3) === 0); } // loop4つめ function is4th(){ global $wp_query; return ((($wp_query->current_post+1) % 4) === 0); }
表示用
<?php if(isFirst()){ ?>loop最初<?php } ?> <?php if(isLast()){ ?>loop最後<?php } ?> <?php if(isOdd()){ ?>loop偶数<?php } ?> <?php if(isEver()){ ?>loop奇数<?php } ?> <?php if(is3rd()){ ?>loop3つめ<?php } ?> <?php if(is4th()){ ?>loop4つめ<?php } ?>
子ページ条件分岐
function.php
function is_subpage() { global $post; if ( is_page() && $post->post_parent ){ $parentID = $post->post_parent; return $parentID; } else { return false; }; };
表示用
<?php if (is_subpage()) { ?>子ページの場合<?php } ?>