wordpress文章采集软件( WordPress非插件实现文章浏览次数统计的方法(图))
优采云 发布时间: 2022-01-25 19:18wordpress文章采集软件(
WordPress非插件实现文章浏览次数统计的方法(图))
文章目录[隐藏]
WordPress文章浏览计数功能必不可少。很多主题都集成了这个功能。如果您的主题没有集成它,您可以使用 WP-Postviews 插件,或者尝试本文中的代码。
WordPress非插件实现文章浏览次数的方法是DH参考大师willin kan的my_visitor插件编写的。刷新文章页面会算一次,比较简单实用。
非插件统计文章视图
1.在主题的functions.php文件中最后一个?>前添加如下代码:
/* 访问计数 */
function record_visitors()
{
if (is_singular())
{
global $post;
$post_ID = $post->ID;
if($post_ID)
{
$post_views = (int)get_post_meta($post_ID, 'views', true);
if(!update_post_meta($post_ID, 'views', ($post_views+1)))
{
add_post_meta($post_ID, 'views', 1, true);
}
}
}
}
add_action('wp_head', 'record_visitors');
/// 函数名称:post_views
/// 函数作用:取得文章的阅读次数
function post_views($before = '(点击 ', $after = ' 次)', $echo = 1)
{
global $post;
$post_ID = $post->ID;
$views = (int)get_post_meta($post_ID, 'views', true);
if ($echo) echo $before, number_format($views), $after;
else return $views;
}
2.使用以下代码调用需要显示计数的地方:
阅读:
获得观看次数最多的文章
如果想获取上述函数中浏览量最高的文章,可以在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_viewed as $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 .= "$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";
}
} else {
$output = "N/An";
}
echo $output;
}
然后使用下面的函数调用:
免责声明:本网站上的所有 文章,除非另有说明或标记,均在本网站 原创 上发布。任何个人或组织未经本站同意,不得复制、盗用、采集、将本站内容发布到任何网站、书籍等媒体平台。如果本站内容侵犯原作者合法权益,您可以联系我们处理。