WordPress自带的条件标签使用说明

2019-02-19 19:00:25王冬梅
WordPress自带的条件标签可以让你依据条件显示不同的内容,比如,你可以检查用户是在首页?是否登陆?

PHP if(语句)
用php的条件语句你可以判断一些事情的真假,如果是真,代码将被执行,否则什么也不发生.看下面的语句,相信你可以理解.


<?php
if(10 == 10):
echo ‘This is true, and will be shown.’;
endif;
if(10 == 15):
echo ‘This is false, and will not be shown.’;
endif;
?>

你同样可以用elseif来增加另一个条件语句,如下:


<?php
if(10 == 11):
echo ‘This is false, and will not be shown.’;
elseif(10 == 15):
echo ‘This is false, and will not be shown.’;
else:
echo ‘Since none of the above is true, this will be shown.’;
endif;
?>

以上就是php的条件语句,好了,下面我们进入WordPress的条件标签.

条件标签怎么起作用
使用WordPress自带的函数如is_home(),你可以轻松的询问WordPress当前的用户是否在首页.WordPress将会回答你是或否,即1或0.


<?php
if( is_home() ):
echo ‘User is on the homepage.’;
else:
echo ‘User is not on the homepage’;
endif;
?>

你可以查询更多关于WordPress的codex条件标签列表.

多个条件的混合使用
有时你查询的条件语句不止一个,你可以使用”和”或”或”即”and”与”or”.


<?php
if( is_home() AND is_page( 5 ) ):
echo ‘User is on the homepage, and the home pages ID is 5′;
endif;
if( is_home() OR is_page( 5 )):
echo ‘User is on the homepage or the page where the ID is 5′;
endif;
?>

什么时候使用条件标签
条件标签非常有用,它可以用来判断用户是否登陆?用户是否使用是ie浏览器?是否有文章显示等等.
看下面的例子:


<?php if ( have_posts() ) : ?>
… posts …
<?php else : ?>
… search field …
<?php endif; ?>

检查是否有文章显示,如果没有,则显示搜索框.
WordPress条件标签的用法举例:


if( is_admin() ):
# User is administator
endif;
if( is_home() AND is_page(’1′) ):
# The user is at the home page and the home page is a page with the ID 1
endif;
if( is_single() OR is_page() ):
# The user is reading a post or a page
endif;
if( !is_home() AND is_page() ):
# The user is on a page, but not the homepage
endif;