ORDER BY custom field value

时间:2016-02-24 作者:dkatwp

基于此处的示例https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

我想修改查询

$q = new WP_Query( array(
\'meta_query\' => array(
    \'relation\' => \'AND\',
    \'state_clause\' => array(
        \'key\' => \'state\',
        \'value\' => \'Wisconsin\',
    ),
    \'city_clause\' => array(
        \'key\' => \'city\',
        \'compare\' => \'EXISTS\',
    ), 
),
\'orderby\' => \'city_clause\') );
能够在以下位置获取所有帖子state 是“威斯康星州”还是timezone 是“中心”订单依据population 描述

2 个回复
最合适的回答,由SO网友:Bruno Cantuaria 整理而成

您可以使用特定的比较操作创建meta\\u查询组,并且由于您希望在单个自定义字段中基于订单,因此可以将订单声明专用于单个meta字段。因此:

$q = new WP_Query( 
    array(
        \'meta_key\' => \'population\', //setting the meta_key which will be used to order
        \'orderby\' => \'meta_value\', //if the meta_key (population) is numeric use meta_value_num instead
        \'order\' => \'DESC\', //setting order direction
        \'meta_query\' => array(
            \'relation\' => \'AND\', //setting relation between queries group
            array(
                \'relation\' => \'OR\', //setting relation between this inside query
                array(
                    \'key\' => \'state\',
                    \'value\' => \'Wisconsin\',
                ),
                array(
                    \'key\' => \'timezone\',
                    \'value\' => \'central\',
                )
            ),
            array(
                \'key\' => \'city\',
                \'compare\' => \'EXISTS\',
            )
        )
    )           
);

SO网友:fischi

可以这样做:

$q = new WP_Query( array(
    \'meta_query\' => array(
        \'relation\' => \'AND\',
        array(
            \'relation\' => \'OR\',
            \'state_clause\' => array(
                \'key\' => \'state\',
                \'value\' => array( \'Wisconsin\' ), //allowed values
                \'compare\' => \'IN\' // state must be in array above
            ),
            \'state_clause\' => array(
                \'key\' => \'timezone\',
                \'value\' => \'central\',
                \'compare\' => \'=\'
            ),
        ),
        \'city_clause\' => array(
            \'key\' => \'city\',
            \'compare\' => \'EXISTS\',
        ), 
    ),
    \'orderby\' => array(
        \'city_clause\' => \'DESC\',
    ),
) );

相关推荐

WooCommerce sort by SKU

所以我试过了https://gist.github.com/bekarice/1883b7e678ec89cc8f4d 在我的网站上。只要所有产品都有SKU,效果就很好。如果产品没有SKU,则根本不会显示。也就是说,是否有其他方法可以按SKU排序,但不要求产品实际具有SKU?