如果查看WP\\u Query的get\\u posts方法,通过输出传递给posts_request
滤器
// Debug the WP_Query sql
add_filter( \'posts_request\', function( $sql ) {
echo "<pre>";
var_dump( $sql );
echo "</pre>";
return $sql;
} );
结果应该如下所示:
string(426) "SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND wp_posts.post_type = \'post\' AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\') AND (
wp_postmeta.meta_key = \'cat1\'
OR
wp_postmeta.meta_key = \'cat2\'
OR
wp_postmeta.meta_key = \'cat3\'
) GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 0, 10"
查询一开始可能看起来是正确的,但事实并非如此。它使用
meta_value
从内部联接的第一行开始
ORDER BY
条款在这种情况下
\'cat1\'
.要改变这种行为,我们可以使用
posts_orderby
钩子更改
ORDER BY
语句并使用
MAX
mysql函数,因此它将使用所有meta\\u值中的最高值,而不仅仅是第一行。
// Filter to alter the orderby sql
function nvdGMCWh_alter_posts_orderby( $sql ) {
return "MAX( $wpdb->postmeta.meta_value+0 ) DESC";
} // - alter_posts_orderby
// Register the filter
add_filter( \'posts_orderby\', \'nvdGMCWh_alter_posts_orderby\' );
// The WP_Query
$res = new WP_Query;
$args = [
\'order\' => \'DESC\',
\'orderby\' => \'meta_value_num\',
\'meta_query\' => [
\'relation\' => \'OR\',
[\'key\' => \'cat1\', \'type\' => \'numeric\'],
[\'key\' => \'cat2\', \'type\' => \'numeric\'],
[\'key\' => \'cat3\', \'type\' => \'numeric\'],
],
]; // - $args
// Execute the query and get the results
$result = $res->query( $args );
// Clean up the filter so it won\'t affect later queries
remove_filter( \'posts_orderby\', \'nvdGMCWh_alter_posts_orderby\' );
// Loop through the results
foreach ( $result as $post ) {
// ... code here
} // - foreach