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 小圖示;而方法二隻是在需要的地方新增。