WordPress 發佈文章一般類型是置頂或者在默認正常。如果在置頂文章或者是 24 小時內最新發布的文章標題加上相應的圖標,不僅可以增加美觀,也可以提高用户瀏覽網站的點擊率。網上有各種漂亮的圖標大家可以自己去搜一下。然後上傳網站替換下面代碼的圖片路徑即可。

添加最新文章圖標方法一:

<?php
function add_title_icon($title)
{
global $post;
$post_date=$post->post_date;
$current_time=current_time('timestamp');
$diff=($current_time-strtotime($post_date))/3600;
$title_icon_new=get_bloginfo('template_directory').'/images/new.gif';
if($diff<24)
{
$title='<img src="'.$title_icon_new.'" />'.$title;
}
return $title;
}
add_filter('the_title','add_title_icon',999);
?>

把以上代碼插入在主題文件夾的 functions.php 裏就行了,可以修改代碼中的 24 為你想要的數值,則超過規定的時間後圖標就會自動消失。

再把 new.gif 圖片文件上傳到當前主題的 images 目錄下面即可。

添加置頂文章圖標方法:

<?php
function add_top_title_icon($title)
{
    global $post;
    $title_icon_top=get_bloginfo('template_directory').'/images/top.gif';
    $sticky = get_option('sticky_posts');
    if($sticky)
    {
    $title=in_array($post->ID,$sticky)?'<img src="'.$title_icon_top.'" />'.$title:$title;
    }
    return $title;
}
add_filter('the_title','add_top_title_icon',999);
?>

使用方法如同添加 new 圖標代碼。

用了以上代碼後,如果頁面列表裏的鏈接也加上了和標題一樣的 new 圖標,可以添加以下代碼解決:

function strip_page_icon_html($content)
{
        $content = preg_replace('@<img(s?)src=(.*?)(s?)/>@','',$content);
        $content = preg_replace('@<img(s?)src=(.*?)(s?)/>@','',$content);
        return $content;
}
add_filter('wp_list_pages','strip_page_icon_html',1000);

加上修正代碼以後,一切應該正常顯示了。

添加最新文章圖標方法二:

<?php
$t1=$post->post_date;
$t2=date("Y-m-d H:i:s");
$diff=(strtotime($t2)-strtotime($t1))/3600;
if($diff<24){echo '<img src="'.get_bloginfo('template_directory').'/images/new.gif" alt='24 小時內最新' />';}
?>

把這段代碼加到需要的地方就行,比如 single.php 中的 <?php the_title(」); ?> 前。

PS:比較一下方法一和方法二的區別,方法一用到了 hook,也就是鈎子,打擊面一大片,比如説首頁和內頁的正文標題處、側邊欄的最新文章、甚至是後台控制板編輯文章的標題前也會自動添加 NEW 小圖標;而方法二隻是在需要的地方添加。