WordPress调用访客最近浏览过的文章

这是在知更鸟博客里面看到一个功能,原理是通过读取浏览器cookie文件,调用显示最近(360天 可选参数)被访问过的(10篇,可选参数)文章 ,需要注意的是,该功能不是统计所有浏览者最近查看过的文章,并没有写进数据库中,每个访客都有自己独有的浏览清单。

效果你可以查看本文章页面"您还看过这些文章哦",同时也可调用至小工具实现。

插件法:下载Last Viewed Posts 插件,可以直接安装并启用该插件,使用更为方便,可以直接将该功能拖到侧边小工具中。文章中调用需要在single模版适当位置加入下面代码;

<?php if (function_exists('zg_recently_viewed')): if (isset($_COOKIE["WP-LastViewedPosts"])) { ?>  
<h2>最近浏览过的文章/h2>  
<?php zg_recently_viewed(); ?>  
<?php } endif; ?>

代码法:提取Last Viewed Posts插件里面的代码,添加至主题functions.php文件中,在小工具中启用即可!

/* Here are some parameters you may want to change: */  
$zg_cookie_expire = 360; // 可选参数  默认360天  
$zg_number_of_posts = 10; // 可选参数 默认10篇文章  
$zg_recognize_pages = true;   
/* Do not edit after this line! */  

function zg_lwp_header() { // Main function is called every time a page/post is being generated  
    if (is_single()) {  
        zg_lw_setcookie();  
    } else if (is_page()) {  
        global $zg_recognize_pages;  
        if ($zg_recognize_pages === true) {  
            zg_lw_setcookie();  
        }  
    }  
}  

function zg_lw_setcookie() { // Do the stuff and set cookie  
    global $wp_query;  
    $zg_post_ID = $wp_query->post->ID; // Read post-ID  
    if (! isset($_COOKIE["WP-LastViewedPosts"])) {  
        $zg_cookiearray = array($zg_post_ID); // If there's no cookie set, set up a new array  
    } else {  
        $zg_cookiearray = unserialize(preg_replace('!s:(d+):"(.*?)";!e', "'s:'.strlen('$2').':"$2";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it  
        if (! is_array($zg_cookiearray)) {  
            $zg_cookiearray = array($zg_post_ID); // If array is fucked up...just build a new one.  
        }  
    }  
    if (in_array($zg_post_ID, $zg_cookiearray)) { // If the item is already included in the array then remove it  
        $zg_key = array_search($zg_post_ID, $zg_cookiearray);  
        array_splice($zg_cookiearray, $zg_key, 1);  
    }  
    array_unshift($zg_cookiearray, $zg_post_ID); // Add new entry as first item in array  
    global $zg_number_of_posts;  
    while (count($zg_cookiearray) > $zg_number_of_posts) { // Limit array to xx (zg_number_of_posts) entries. Otherwise cut off last entry until the right count has been reached  
        array_pop($zg_cookiearray);  
    }  
    $zg_blog_url_array = parse_url(get_bloginfo('url')); // Get URL of blog  
    $zg_blog_url = $zg_blog_url_array['host']; // Get domain  
    $zg_blog_url = str_replace('www.', '', $zg_blog_url);  
    $zg_blog_url_dot = '.';  
    $zg_blog_url_dot .= $zg_blog_url;  
    $zg_path_url = $zg_blog_url_array['path']; // Get path  
    $zg_path_url_slash = '/';  
    $zg_path_url .= $zg_path_url_slash;  
    global $zg_cookie_expire;  
    setcookie("WP-LastViewedPosts", serialize($zg_cookiearray), (time()+($zg_cookie_expire*86400)), $zg_path_url, $zg_blog_url_dot, 0);  
}  

function zg_recently_viewed() { // Output  
    echo '<ul class="viewed_posts">';  
    if (isset($_COOKIE["WP-LastViewedPosts"])) {  
        //echo "Cookie was set.<br/>";  // For bugfixing - uncomment to see if cookie was set  
        //echo $_COOKIE["WP-LastViewedPosts"]; // For bugfixing (cookie content)  
        $zg_post_IDs = unserialize(preg_replace('!s:(d+):"(.*?)";!e', "'s:'.strlen('$2').':"$2";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it  
        foreach ($zg_post_IDs as $value) { // Do output as long there are posts  
            global $wpdb;  
            $zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' LIMIT 1");  
            foreach($zg_get_title as $zg_title_out) {  
                echo "<li><a href="". get_permalink($value+0) . "" title="". $zg_title_out->post_title . "">". $zg_title_out->post_title . "</a></li>n"; // Output link and title  
            }  
        }  
    } else {  
        //echo "No cookie found.";  // For bugfixing - uncomment to see if cookie was not set  
    }  
    echo '</ul>';  
}  

function zg_lwp_widget($args) { // Widget output  
    extract($args);  
    $options = get_option('zg_lwp_widget');  
    $title = htmlspecialchars(stripcslashes($options['title']), ENT_QUOTES);  
    $title = emptyempty($options['title']) ? 'Last viewed posts' : $options['title'];  
    if (isset($_COOKIE["WP-LastViewedPosts"])) {  
        echo $before_widget . $before_title . $title . $after_title;  
        zg_recently_viewed();  
        echo $after_widget;  
    }  
}  

function zg_lwp_widget_control() { // Widget control  
    $options = $newoptions = get_option('zg_lwp_widget');  
    if ( $_POST['lwp-submit'] ) {  
        $newoptions['title'] = strip_tags(stripslashes($_POST['lwp-title']));  
    }  
    if ( $options != $newoptions ) {  
        $options = $newoptions;  
        update_option('zg_lwp_widget', $options);  
    }  
    $title = attribute_escape( $options['title'] );  
    ?>  
    <p><label for="lwp-title">  
    <?php _e('Title:') ?> <input type="text" style="width:250px" id="lwp-title" name="lwp-title" value="<?php echo $title ?>" /></label>  
    </p>  
    <input type="hidden" name="lwp-submit" id="lwp-submit" value="1" />  
    <?php  
}  

function zg_lwp_init() { // Widget init  
    if ( !function_exists('register_sidebar_widget') )  
        return;  
    register_sidebar_widget('Last Viewed Posts','zg_lwp_widget');  
    register_widget_control('Last Viewed Posts','zg_lwp_widget_control', 250, 100);  
}  

add_action('get_header','zg_lwp_header');  
add_action('widgets_init', 'zg_lwp_init');

调用方法和插件一样,都是<?php zg_recently_viewed(); ?>在起作用,不过你还可以给这些文章添加简单的CSS样式,比如像我这样的并排显示10篇文章。

/*最近浏览过的文章*/  
.recently {padding: 10px 0 10px 15px;width: 690px;}  
.recently ul {list-style: none outside none;}  
.recently ul li {border-bottom: 1px dashed #DADADA;float: left;line-height: 26px;list-style: none outside none;margin: 0 12px 0 0;text-indent: 0;width: 325px;}
展开评论