简体   繁体   English

如何在Wordpress中按自定义字段值排序帖子

[英]How to order posts by custom field value in wordpress

I wanna order posts by custom field value which now currently is posts view number. 我想按自定义字段值来排序帖子,而该字段值现在是帖子查看次数。 I tried with the following code 我尝试了以下代码

$queried_object = get_queried_object();
$args = array(
        'post_type'  => 'product',
        'term'  => $queried_object->slug,
        'meta_query' => array(
            array(
                'key'     => 'product_views_count',
                'orderby' => 'meta_value_num',
                'order' => DESC,
            )
        ),
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'terms' => array(
                    $queried_object->term_id
                )
            )
        )
    );
$query = new WP_Query($args);

So with this am getting the current category posts but still it did not sort the posts by product_views_count custom field value. 因此,这样可以获取当前类别的帖子,但仍然无法按照product_views_count自定义字段值对帖子进行排序。

Any idea what is wrong here? 知道这里有什么问题吗? Thanks in advance. 提前致谢。

I think you have just misplaced the orderby argument. 我认为您刚刚放错了orderby参数。 It goes in the top level. 它在顶层。 You also need to add a meta_key argument there too so it knows what to be ordering by. 您还需要在meta_key添加meta_key参数,以便它知道要排序的内容。

I just slightly modified the code from your question to what you need. 我只是将代码从您的问题略微修改为所需的内容。 It's untested but should work just fine. 它未经测试,但应该可以正常工作。

$queried_object = get_queried_object();
$args = array(
        'post_type'     => 'product',
        'term'          => $queried_object->slug,
        'orderby'       => 'meta_value_num',
        'order'         => DESC,
        'meta_key'      => 'product_views_count',
        'meta_query'    => array(
            array(
                'key'       => 'product_views_count'
            )
        ),
        'tax_query'     => array(
            array(
                'taxonomy'  => 'product_cat',
                'terms'     => array(
                    $queried_object->term_id
                )
            )
        )
    );
$query = new WP_Query($args);

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

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