wordpress小技巧

if(is_home())等无效/失效的解决办法:

<?php if ( is_home() ) { ?> 我只会在首页显示 <?php } ?>
<?php if ( is_singular() ) { ?> 我只会在文章页面显示 <?php } ?>

以往我们都是这样使用这种函数的,其中is_home()函数在首页的时候会返回一个 true,is_singular()同理。我们往往会在主题的header.php或footer.php等经常遇见。但是如果在调用该函数之前有个 query_posts(); 则会让它失效,原因是 is_home,is_singular()等这种 is_ 前缀的都是基于主循环来判断,而 query_posts(); 会让其偏离主循环。当然有解决方案了:

解决方案是:在 is_home()之前加一个 wp_reset_query();类似于这样:

<?php wp_reset_query(); if ( is_home() ) { ?>
我只会在首页显示, 而且我不怕
query_posts()哦
<?php } ?>

wp文章添加new的提示:

 

首先在主题的index.php种找到标题的显示代码,类似于
<h2><a href=”<?php the_permalink() ?>” title=”<?php the_title(); ?>”><?php the_title(); ?></a></h2>
然后在<?php the_title(); ?>和</a>之间(位置也可以根据自己需求改变)加上如下代码:
<em><?php $t1=$post->post_date; $t2=date(“Y-m-d H:i:s”); $diff=(strtotime($t2)-strtotime($t1))/3600; if($diff<24){echo ” New!”;} ?></em>
简单说一下,以上代码判断文章发布的时间如果小于24小时,则显示“New!”,你也可以改成你想要的时间。然后加上em样式:(仅供参考)
.post em{font-size:14px; color:#FF0242;}
如果你不想显示文字而想显示图片的话,可以将{echo ” New!”;}改成:
{echo ‘<img src=”‘.get_bloginfo(‘template_directory’).’/images/new.gif” />’;}

 

也可以这样:

<?php
$t1=$post->post_date;
$t2=date(“Y-m-d H:i:s”);
$diff=(strtotime($t2)-strtotime($t1))/7200;
if($diff<24){echo ‘<img src=”‘.get_bloginfo(‘template_directory’).’/images/new.gif” alt=”较新的文章” title=”较新的文章” />’;}
?>