有时候,我们会发现有些主题在添加 is_home()、is_single()、is_singular() 之类的判断时会失效,这种情况多发生在CMS类主题,其实都是主题制作者代码写作习惯不好造成的,这类主题往往用到了query_posts函数,而使用完成后他们并没有用wp_reset_query()函数重置,所以就造成了你在其它很多地方添加的判断代码失效,解决示例如下:
以下是一个错误的示例,咋一看好像没什么问题,使用起来也基本没问题:
<h3><?php _e('最新文章'); ?></h3> <ul> <?php query_posts('showposts=10&caller_get_posts=1'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li><a rel="bookmark" href="<?php the_permalink() ?>" title="<?php the_title() ?>"><?php the_title() ?></a></li> <?php endwhile; endif; ?> </ul>
正确的代码应该如下:
<h3><?php _e('最新文章'); ?></h3> <ul> <?php query_posts('showposts=10&caller_get_posts=1'); ?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <li><a rel="bookmark" href="<?php the_permalink() ?>" title="<?php the_title() ?>"><?php the_title() ?></a></li> <?php endwhile; endif; wp_reset_query(); ?> </ul>
两者之间的差别就是后者多加了个wp_reset_query()函数,这就类似if要用endif结束,while要用endwhile结束,foreach要用endforeach结束,如果代码写作习惯好就不会出现这种麻烦。