在本教程中,我们将看到如何在 WordPress的 使用没有任何插件的自定义代码。我们要做的就是创建两个简单的方法,分别为特定帖子添加一个计数并获取计数。
将观看次数添加到发布
我们需要做的第一件事是在 functions.php file. The functionality will be like the method will accept an argument ID
and by that ID the post_meta
will be fetched for 'post_views_count'
.
如果找不到职位数,则将其设置为0,如果找到职位数,则它将增加职位数。
functions.php
/**
* function to count views.
* @param {number} $postID : post ID
*/
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
获取发布的观看次数
接下来要做的是在同一方法中创建一个方法 functions.php file which will retrieve the count of the user visits of a particular post.The functionality will be like the method will accept an argument ID
and by that ID the post_meta
will be fetched for 'post_views_count'
.
如果未找到发布元,则返回“ 0次观看”,如果找到,则返回e.x的计数。 120视图。
functions.php
/**
* function to get the post visits count.
* @param {number} $postID : post ID
* @return {string} return post visits count
*/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
在WordPress模板中显示帖子视图
要显示帖子访问计数,我们必须首先添加该计数,以便每当查看单个帖子时,它都会通过我们的方法将计数增加到数据库中。
您可以添加方法 single.php 如果您的模板包含它,或者您可以添加 index.php 文件,因为它必须在那里。
index.php / single.php
<?php get_header(); ?>
<?php
if(have_posts()) :
while (have_posts()) :the_post();
setPostViews(get_the_ID()); // Add the post count when the post is viewed
?>
/* ...Your Blog Content... */
/* Display Where Ever You Want In Your Template */
<?= getPostViews(get_the_ID()) ?>
/* ...Your Blog Content... */
<?php
endwhile;
endif;
?>
获取有关的更多教程 WordPress的