【发布时间】:2014-03-11 16:49:55
【问题描述】:
我搜索了该网站,但没有找到我要查找的内容。我有一个正常运行的代码,只有输出是错误的,这就是我认为它不起作用的原因。
到目前为止,这是我的代码:
这是在函数中:
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 to 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);
}
}
// Add it to a column in WP-Admin - (Optional)
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2);
function posts_column_views($defaults){
$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){
if($column_name === 'post_views'){
echo getPostViews(get_the_ID());
}
}
$args = array( 'numberposts' => 4, /* get 4 posts, or set -1 for all */
'orderby' => 'meta_value_num', /* this will look at the meta_key you set below */
'meta_key' => 'post_views_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish'
);
$myposts = get_posts( $args );
foreach( $myposts as $mypost ) {
$id = $mypost->ID;
$post_views = intval($post->views);
$post_title = get_the_title($post);
$post_title = $post->post_title;
}
非常感谢您。
【问题讨论】:
-
您好,非常感谢您的快速回复。我遇到的错误是帖子没有按浏览次数排序,而是按默认 WP 排序。我会尽快附上截图。
-
imageshack.com/a/img196/2782/xyhk.png 这是我希望实现的一个例子。登出网站后多次点击“开发组”帖子,看不到可以归为浏览量最多的帖子。
标签: php wordpress sorting post output