如果你的网站内容非常好,肯定会有一些忠实访客。忠实访客一般会定期访问一次你的网站,看看有没有新文章。

本文会来教你,怎么给访客上次来之后更新的文章打上标记。标记之后,会帮助访客更加容易找到需要的新文章。

首先把下边的代码加到当前主题的 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 提醒访客上次来访后更新的文章