首次发布后完全编辑的问题是,要订购元数据,WordPress需要\'meta_key\'
in query设置为某物。但如果你\'meta_key\'
然后WordPress会添加如下内容
AND ( wp_postmeta.meta_key = \'the_meta_key\' )
至
WHERE
SQL子句;比如
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )
至
join
条款。所以查询只返回包含该元查询的帖子。
一旦您在后端工作,并且调用get_post_meta( $postid, \'featured\', true)
对于每一篇显示该列的帖子来说,性能并不是一个大问题。由于get-meta函数上的WordPress缓存,请多次调用它。
因此,我们的想法是获取所有帖子(不在meta键上添加过滤器),然后使用\'posts_results\'
勾选并订购查看“特色”元键的帖子。
我刚用完过滤器就把它取下来。
add_filter( \'posts_results\', \'order_by_featured\', PHP_INT_MAX, 2 );
function order_by_featured ( $posts, $query ) {
// run only on admin, on main query and only if \'orderby\' is featured
if ( is_admin() && $query->is_main_query() && $query->get(\'orderby\') === \'featured\' ) {
// run once
remove_filter( current_filter(), __FUNCTION__, PHP_INT_MAX, 2 );
$nonfeatured = array();
$featured = array();
foreach ( $posts as $post ) {
if ( get_post_meta( $post->ID, \'featured\', TRUE ) ) {
$featured[] = $post;
} else {
$nonfeatured[] = $post;
}
}
$order = strtoupper( $query->get(\'order\') ) === \'ASC\' ? \'DESC\' : \'ASC\';
// if order is ASC put featured at top, otherwise put featured at bottm
$posts = ( $order === \'ASC\' )
? array_merge( $nonfeatured, $featured )
: array_merge( $featured, $nonfeatured );
}
return $posts;
}
此外,我在
\'pre_get_post\'
使用
\'ASC\'
如果查询中未设置订单,则作为默认订单:
add_action( \'pre_get_posts\', function( $query ) {
// if no order is set set order to ASC
if (
is_admin() && $query->is_main_query()
&& $query->get(\'orderby\') === \'featured\'
&& $query->get(\'order\') === \'\'
) {
$query->set( \'order\', \'ASC\' );
}
});