如果您想创建自己的WP\\U查询,那么您可以这样做:
<?php
$args = array(
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\',
\'meta_key\' => \'price\'
);
$new_query = new WP_Query( $args );
?>
参见文档中的示例:
https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
由于您使用的是Mainloop,因此需要采取一些不同的行动:
<?php
add_action( \'pre_get_posts\', \'order_by_price\' );
function order_by_price( $query ){
if( ! $query->is_main_query() ) //If its not the main query return
return;
$query->set( \'order\', \'asc\' );
$query->set( \'orderby\', \'meta_value_num\' );
$query->set( \'meta_key\', \'price\' );
}
?>
这将作用于每个主回路。所以要小心。也许你希望这只适用于特定的职位类型。在这种情况下,应首先检查:
<?php
add_action( \'pre_get_posts\', \'order_by_price\' );
function order_by_price( $query ){
if( ! $query->is_main_query() ) //If its not the main query return
return;
if( \'product\' != $query->get( \'post_type\' ) ) //Apply only for \'product\' post types
return;
$query->set( \'order\', \'asc\' );
$query->set( \'orderby\', \'meta_value_num\' );
$query->set( \'meta_key\', \'price\' );
}
?>
还要检查此Actionhook的文档:
https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts