简体   繁体   English

按元值排序帖子-Wordpress

[英]Order posts by meta value - wordpress

I have a meta key and value that keeps a track of people that like the post. 我有一个元键和值,可以跟踪喜欢该帖子的人。 However if a post has no likes it has no meta key or value. 但是,如果帖子没有喜欢,则没有元键或值。 My WP query is thus: 因此,我的WP查询为:

$args = array(
  'post_type' => 'post',
  'meta_key' => '_post_like_count',
  'orderby' => 'meta_value_num',
  'order' => 'DESC',
  'posts_per_page' => 3
);
$pop_posts = new WP_Query( $args );

The query above just doesn't bring back the right results. 上面的查询只是没有带回正确的结果。

I've tried permutations of the $args below but with still no joy: 我尝试了下面$ args的排列,但仍然没有喜悦:

$args = array(
    'post_type' => 'post',
     'meta_query' => array(
           'relation' => 'OR',
            array(
                    'key' => '_post_like_count',
                    'compare' => 'EXISTS',
                ),
            ),
    'meta_key' => '_post_like_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    posts_per_page' => '3',              
);

Both the $args above bring back results - just not the results of the posts with the most likes. 上面的$ args都带回结果-而不是最喜欢的帖子的结果。

Can anyone help? 有人可以帮忙吗?

I've spent long time with the meta queries and it usually complicates things. 我花了很长时间处理元查询,它通常使事情复杂化。

My advice would be using direct connection to the database through $wpdb, for being much easier. 我的建议是使用通过$ wpdb直接连接到数据库的方式,因为这样做容易得多。 Take this as a start: 以此为起点:

global $wpdb;
$posts_with_most_likes = $wpdb->get_results(
                "
                SELECT _post_like_count
                FROM $wpdb->postmeta
                ORDER BY meta_value_num
                "
            );

Thank you Loai Nagati. 谢谢Loai Nagati。 I modified your answer to the following which worked perfectly. 我修改了您对以下内容的回答,它们非常有效。

$posts_with_most_likes = $wpdb->get_results(
    "
    SELECT post_id
    FROM $wpdb->postmeta
    WHERE meta_key = '_post_like_count'
    ORDER BY meta_value DESC
    LIMIT 3
    "
);

Thanks again! 再次感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM