WordPress获取浏览次数最多的文章代码

2015-12-26 00:32 阅读 29 次 评论关闭

WordPress如何实现获取浏览次数最多的文章?如果要获取上面的函数统计出来的浏览次数最多的文章,那就要先在functions.php文件中创建一个获取阅读文章次数的函数,然后再在需要的地方进行此函数的调用即可。具体的WordPress获取浏览次数最多的文章实现方法如下:

在 functions.php文件的最后一个 ?> 前面添加下面的代码

/// get_most_viewed_format
/// 函数作用:取得阅读最多的文章
function get_most_viewed_format($mode='',$limit=10,$show_date=0,$term_id=0,$beforetitle='(',$aftertitle=')',$beforedate='(',$afterdate=')',$beforecount='(',$aftercount=')'){
global$wpdb,$post;
$output='';
$mode=($mode=='') ? 'post':$mode;
$type_sql=($mode!='both') ? "AND post_type='$mode'":'';
$term_sql=(is_array($term_id)) ? "AND $wpdb->term_taxonomy.term_id IN (".join(',',$term_id).')':($term_id!=0 ? "AND $wpdb->term_taxonomy.term_id = $term_id":'');
$term_sql.=$term_id ? " AND $wpdb->term_taxonomy.taxonomy != 'link_category'":'';
$inr_join=$term_id ? "INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)":'';

// database query

$most_viewed=$wpdb->get_results("SELECT ID, post_date, post_title, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) $inr_join WHERE post_status = 'publish' AND post_password = '' $term_sql $type_sql AND meta_key = 'views' GROUP BY ID ORDER BY views DESC LIMIT $limit");
if($most_viewed){
foreach($most_viewedas$viewed){
$post_ID=$viewed->ID;
$post_views=number_format($viewed->views);
$post_title= esc_attr($viewed->post_title);
$get_permalink= esc_attr(get_permalink($post_ID));
$output.="<li>$beforetitle$post_title$aftertitle";
if($show_date){
$posted=date(get_option('date_format'),strtotime($viewed->post_date));
$output.="$beforedate $posted $afterdate";
}
$output.="$beforecount $post_views $aftercount</li>";
}
}else{
$output="<li>N/A</li>n";
}
echo$output;
}

然后使用下面的函数调用

<?php get_most_viewed_format();?>
版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:WordPress获取浏览次数最多的文章代码 | 猎微网

评论已关闭!