之前在網上找到的一些有關WordPess熱門文章都是根據評論數多少來調用的,雖然安裝的WP-PostViews Plus這個統計文件瀏覽數插件帶有調用文章功能,但卻沒有辦法規定時間段,比如7天之內還是一個月之內。
使用下面代碼的前提條件是你必須安裝有WP-PostViews Plus這款插件,可更改代碼中的'-7 days'這個7數字來獲取多天內的熱門點擊文章。
function most_viewed($mode = '', $limit = 10, $chars = 0, $display = true) {
global $wpdb, $post;
$views_options = get_option('PVP_options');
$where = '';
$temp = '';
$output = '';
if(!empty($mode) && $mode != 'both') {
$where = "post_type = '$mode'";
} else {
$where = '1=1';
}
$most_viewed = $wpdb->get_results("SELECT DISTINCT $wpdb->posts.*, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE post_date > '" . date('Y-m-d', strtotime('-7 days')) . "' AND $where AND post_status = 'publish' AND meta_key = 'views' AND post_password = '' ORDER BY views DESC LIMIT $limit");
if($most_viewed) {
foreach ($most_viewed as $post) {
$post_views = intval($post->views);
$post_title = get_the_title();
if($chars > 0) {
$post_title = snippet_text($post_title, $chars);
}
// Downloads By http://www.veryhuo.com
$post_excerpt = views_post_excerpt($post->post_excerpt, $post->post_content, $post->post_password, $chars);
$post_content = get_the_content();
$temp = stripslashes($views_options['most_viewed_template']);
$temp = str_replace("%VIEW_COUNT%", number_format_i18n($post_views), $temp);
$temp = str_replace("%POST_TITLE%", $post_title, $temp);
$temp = str_replace("%POST_EXCERPT%", $post_excerpt, $temp);
$temp = str_replace("%POST_CONTENT%", $post_content, $temp);
$temp = str_replace("%POST_URL%", get_permalink(), $temp);
$output .= $temp;
//$output=stripslashes($views_options['most_viewed_template']);
}
} else {
$output = '<li>N/A</li>'."";
}
if($display) {
echo $output;
} else {
return $output;
}
}
講上面的代碼放到你主題下的Function.php文件中,在須要調用的地方通過下面的代碼調用即可,其中10表示調用10篇文章,可根據你的需要自定義調用多少篇。
<?php
if (function_exists('get_most_viewed') & function_exists('most_viewed')){
most_viewed('post',10);
}
?>