使用元值订购 Wordpress 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11100473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:56:45  来源:igfitidea点击:

Ordering Wordpress posts with meta values

wordpress

提问by user537137

I have this code below that basically creates 4 links to allow me to sort posts on the front end.

我在下面有这段代码,它基本上创建了 4 个链接,让我可以在前端对帖子进行排序。

        <div class="sort">
            Sort projects by:
            <a href="http://mydomain.com/find-work/" >Latest Projects</a>
            <a href="http://mydomain.com/find-work/?order=asc&orderby=date" >Ending Soon</a>
            <a href="http://mydomain.com/find-work/?order=asc&orderby=meta_value_num&meta_key=proj_budget" >Budget Low</a>
            <a href="http://mydomain.com/find-work/?order=desc&orderby=meta_value_num&meta_key=proj_budget" >Budget High</a>
        </div>

        <?php   $my_query = new WP_Query( array( 
                        'post_type' => 'project',
                        'orderby' => get_query_var('orderby'),
                        'order' => get_query_var('order'),
                        ));      
                while ( $my_query->have_posts() ) : $my_query->the_post(); ?>

The second link, ordering by date works fine but the two links to order by meta values is not working. I am obviously missing something in my query but for the life of me can't work it out.

第二个链接,按日期排序工作正常,但按元值排序的两个链接不起作用。我显然在我的查询中遗漏了一些东西,但我一生都无法解决。

Any ideas??

有任何想法吗??

回答by Jure C.

It's a bit magical with meta values:

元值有点神奇:

$my_query = new WP_Query( array( 
                    // 'post_type' => 'project',
                    'meta_key' => 'proj_budget',
                    'orderby' => 'meta_value_num'
                    ));      

All the possible values are explained in codex: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

所有可能的值都在代码中进行了解释:http: //codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

回答by Erik van de Ven

It's quite simple:

这很简单:

new WP_Query( array( 
              //I used meta_value_num below, because it's about a numeric field
              //if you don't have a numeric field, just use meta_value
              "orderby" => 'meta_value_num',
              "meta_key" => 'price',
              "order" => 'DESC'
              ));