您可以这样做:
使用meta_query
参数查询包含元数据的两篇文章_my_column
(或者不管什么是元键)和没有元键的帖子(即数据库中不存在)。
将自定义名称(即数组键)与上述元查询子句一起使用,然后在orderby
参数
请参见Query improvements in WP 4.2: ‘orderby’ and ‘meta_query’ 了解更多详细信息。
因此,与其使用meta_key
参数:
注意:我看到您使用meta_value_num
, 所以我用了\'type\' => \'NUMERIC\'
确保元值被视为(有符号)整数
如果您不想/需要保留现有的元查询(在$query
对象):
$query->set( \'meta_query\', array(
\'relation\' => \'OR\',
// Clause 1, named my_column_exists:
// Query posts that do have the metadata _my_column.
\'my_column_exists\' => array(
\'key\' => \'_my_column\', // meta key
\'compare\' => \'EXISTS\',
\'type\' => \'NUMERIC\',
),
// Clause 2, named my_column_not_exists:
// OR that do NOT have the metadata.
\'my_column_not_exists\' => array(
\'key\' => \'_my_column\', // meta key
\'compare\' => \'NOT EXISTS\',
\'type\' => \'NUMERIC\',
),
) );
$query->set( \'orderby\', array(
// Sort by the _my_column metadata first.
\'my_column_not_exists\' => \'DESC\',
// Then if you want, by the post date, title, etc.
\'date\' => \'ASC\',
) );
否则(要保留现有的元查询),可以执行以下操作:
$query->set( \'meta_query\', array(
// Note: Here the \'relation\' defaults to AND.
// Clause 1, unnamed.
array(
\'relation\' => \'OR\',
// Sub-clause 1, named my_column_exists:
// Query posts that do have the metadata _my_column.
\'my_column_exists\' => array(
\'key\' => \'_my_column\', // meta key
\'compare\' => \'EXISTS\',
\'type\' => \'NUMERIC\',
),
// Sub-clause 2, named my_column_not_exists:
// OR that do NOT have the metadata.
\'my_column_not_exists\' => array(
\'key\' => \'_my_column\', // meta key
\'compare\' => \'NOT EXISTS\',
\'type\' => \'NUMERIC\',
),
),
// Clause 2, unnamed.
// Include the existing meta queries.
(array) $query->get( \'meta_query\' ),
) );
$query->set( \'orderby\', array(
// Sort by the _my_column metadata first.
\'my_column_not_exists\' => \'DESC\',
// Then if you want, by the post date, title, etc.
\'date\' => \'ASC\',
) );