使用PRE_GET_POSTS挂接对归档视图进行排序

时间:2016-08-15 作者:mokiSRB

我有这样的功能:

//sorting archive query by pinned posts
function archive_sort_pinned($query){
    $option = get_option(\'hsa_story_cats\');
    $current_category = get_queried_object();

    if(!is_admin() && $query->is_main_query() && is_category($option)){
        $query->set(\'meta_query\', array(
            \'relation\' => \'OR\',
            array(
                \'key\'       => \'story_cat_order_\'. $current_category->term_id,
                \'compare\'   => \'EXISTS\',
            ),
            array(
                \'key\'       => \'story_cat_order_\'. $current_category->term_id,
                \'compare\'   => \'NOT EXISTS\',
                \'value\' => \'\'
            )
        ));
        $query->set(\'orderby\', array( \'meta_value_num\' => \'ASC\', \'date\' => \'DESC\' ));
        $query->set(\'meta_key\',\'story_cat_order_\'. $current_category->term_id);
    }
}
add_action(\'pre_get_posts\', \'archive_sort_pinned\');
问题是:这将只返回带有键的帖子story_cat_order_<cat_id>, 当我删除最后一行时meta key 然后我得到了所有的帖子,但它们没有被订购。

我想用这个来点meta_key 如果他们有,或者如果没有,则按日期meta_key.

1 个回复
最合适的回答,由SO网友:mokiSRB 整理而成

我用不同的方法解决了这个问题。我用过posts_joinposts_orderby 过滤器。

Do not forget to cast meta value as unsiged to avoid string ordering instead of int.

//edit query join
function hsa_story_join($join){

    global $wpdb;
    $option = get_option(\'hsa_story_cats\');
    if(!is_admin() && is_category($option)) {
        $current_category = get_queried_object();
        $join .= " LEFT JOIN (SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE meta_key = \'story_cat_order_". $current_category->term_id ."\') AS hsam ON $wpdb->posts.ID = hsam.post_id ";
    }
    return $join;
}
add_filter(\'posts_join\', \'hsa_story_join\');

//edit query order by
function hsa_story_order($order){

    $option = get_option(\'hsa_story_cats\');
    if(!is_admin() && is_category($option)) {
        $current_category = get_queried_object();
        $order = " IF(hsam.meta_key=\'story_cat_order_". $current_category->term_id ."\', cast(hsam.meta_value as unsigned), 99999) ASC, " . $order;
    }

    return $order;
}
add_filter(\'posts_orderby\', \'hsa_story_order\',99,1);