如果你的網站內容非常好,肯定會有一些忠實訪客。忠實訪客一般會定期訪問一次你的網站,看看有沒有新文章。

本文會來教你,怎麼給訪客上次來之後更新的文章打上標記。標記之後,會幫助訪客更加容易找到需要的新文章。

首先把下邊的代碼加到當前主題的 functions.php(瞭解更多) 裏:

/**

*WordPress 提醒訪客上次來訪後更新的文章

*/

function Bing_lastvisit_the_title( $title, $id ){

if( !in_the_loop() || is_singular() || get_post_type( $id ) == 'page' ) return $title;

$cookiename = COOKIEHASH . '_lastvisit';

if( !isset( $_COOKIE[$cookiename] ) || empty( $_COOKIE[$cookiename] ) ) return $title;

$lastvisit = $_COOKIE[$cookiename];

$publish_date = get_post_time( 'U', true, $id );

if( $publish_date > $lastvisit ) $title .= '(新)';

return $title;

}

add_filter( 'the_title',  'Bing_lastvisit_the_title', 12, 2 );

//設置 Cookie

function Bing_lastvisit_set_cookie(){

if( is_admin() ) return;

$current = current_time( 'timestamp', 1 );

setcookie( COOKIEHASH . '_lastvisit', $current, time() + 60 + 60 * 24 * 7, COOKIEPATH, COOKIE_DOMAIN );

}

add_action( 'init', 'Bing_lastvisit_set_cookie' );

 

添加之後,每個訪客訪問都會被添加一個 Cookie,記錄他們最後的訪問時間,如果文章的時間在 Cookie 記錄的時間的後邊,則打上 「新」 標記。

WordPress 提醒訪客上次來訪後更新的文章