【问题标题】:Sort posts by most viewed Wordpress按浏览次数最多的 Wordpress 对帖子进行排序
【发布时间】: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


【解决方案1】:

尝试将'orderby' => 'meta_value_num' 更改为'orderby' => 'meta_value meta_value_num''orderby' => 'meta_value_num meta_value'。我已经看到这个解决方案对某些人有用。

我实际上遇到了与此非常相似的问题。尝试转储 SQL(此处为教程:http://ben.lobaugh.net/blog/45390/wordpress-how-to-view-the-sql-query-generated-by-wp_query)并查看它的外观。当我遇到这个问题时,我发现 SQL 是错误的。

【讨论】:

  • 感谢您的回复。我已经这样做了,但它仍然不会按观看次数最多的方式排序。
  • @user1805959 你能把 WP_Query 生成的 SQL 转储到这里吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多