指定meta\\u键时,query_posts()
在wp\\u posts和wp\\u postmeta表之间进行内部联接。这意味着,对于您指定的键,任何没有任何元值的帖子都不会在该查询中返回。
为了满足您的需要,您应该使用您在问题中发布的相同查询,但要更改orderby=meta_value
到orderby=meta_value_num
. 然后,您可以过滤“get\\u meta\\u sql”,使连接返回所有帖子。将以下内容添加到函数中。php:
<?php
function wpse_55791_custom_order($clauses)
{
global $wp_query;
// check for order by custom_order
if ($wp_query->get(\'meta_key\') == \'custom_order\' && $wp_query->get(\'orderby\') == \'meta_value_num\')
{
// change the inner join to a left join,
// and change the where so it is applied to the join, not the results of the query
$clauses[\'join\'] = str_replace(\'INNER JOIN\', \'LEFT JOIN\', $clauses[\'join\']).$clauses[\'where\'];
$clauses[\'where\'] = \'\';
}
return $clauses;
}
add_filter(\'get_meta_sql\', \'wpse_55791_custom_order\', 10, 1);
?>
编辑:若要修复排序,请尝试将其与上述内容一起添加:
<?php
function wpse_55791_custom_orderby($orderby)
{
global $wp_query, $wpdb;
// check for order by custom_order
if ($wp_query->get(\'meta_key\') == \'custom_order\' && $wp_query->get(\'orderby\') == \'meta_value_num\')
{
$orderby = "{$wpdb->postmeta}.meta_value=\'\', ".$orderby;
}
return $orderby;
}
add_filter(\'posts_orderby\', \'wpse_55791_custom_orderby\', 10, 1);
?>
编辑两个-2个循环:
我会这样做:
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
$ordered_posts = new WP_Query(array(
\'paged\' => $paged,
\'cat\' => 7,
\'posts_per_page\' => 24,
\'meta_key\' => \'custom_order\',
\'orderby\' => \'meta_value_num\',
\'order\' => \'ASC\',
));
$unordered = new WP_Query(array(
\'cat\' => 7,
\'paged\' => $paged,
\'posts_per_page\' => 24 - $ordered_posts->post_count,
));
if ($ordered_posts->have_posts()) :
while ($ordered_posts->have_posts()) : $ordered_posts->the_post();
// loop 1
endwhile;
endif;
if ($unordered_posts->have_posts()) :
while ($unordered_posts->have_posts()) : $unordered_posts->the_post();
// loop 2
endwhile;
endif;
请注意,如果您认为有超过24篇已排序的文章,那么paged变量对于未排序的文章将是错误的;您可能需要设置一个全局变量来跟踪到目前为止显示了多少已排序/未排序的帖子,并使用它来计算单独的
$paged
每种类型的值。