例如:https://ww.abcd.com/news/wp-json/wp/v2/posts/007 将提供有关ID为007的帖子的所有详细信息,但不提供该帖子的查看次数,同样也不会提供该帖子中包含的图片。
如何在不使用任何外部插件的情况下获取这些详细信息?
答案 0 :(得分:0)
是的,你可以这样做:
1) - 将此代码添加到wordpress主题的functions.php
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';
}
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);
}
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
2) - 此部分跟踪视图代码将设置帖子视图。只需将此代码段放在wordpress循环内的single.php
setPostViews(get_the_ID());
3) - 显示视图计数:
echo getPostViews(get_the_ID());