get_categories以自定义字段的顺序发布

时间:2017-07-14 18:26:43

标签: php wordpress

我有一些研究,发现这个get_categories order by last post

这几乎是我想要的,但我希望通过自定义字段(由插件高级自定义字段创建)的帖子顺序,让我们说明按日期排序的帖子(自定义字段),然后是最大的自定义类别字段值帖子将首先出现,是否可用?

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

function get_sorted_categories( $custom_field, $args = array() ){
    global $wpdb;

    $category = get_categories( $args );

    $custom_field = esc_sql( $custom_field );

    $q = $wpdb->get_results("SELECT tax.term_id FROM `{$wpdb->prefix}term_taxonomy` tax
    INNER JOIN `{$wpdb->prefix}term_relationships` rel ON rel.term_taxonomy_id = tax.term_id
    INNER JOIN `{$wpdb->prefix}posts` post ON rel.object_id = post.ID 
    INNER JOIN `{$wpdb->prefix}postmeta` meta ON meta.post_id = post.ID AND meta.meta_key = '{$custom_field}'
    WHERE tax.taxonomy = 'category' AND post.post_type = 'post' AND post.post_status = 'publish' AND  ORDER BY meta.meta_value DESC");

    $sort = array_flip( array_unique( wp_list_pluck( $q, 'term_id' ) ) );

    usort( $category, function( $a, $b ) use ( $sort, $category ) {
        if( isset( $sort[ $a->term_id ], $sort[ $b->term_id ] ) && $sort[ $a->term_id ] != $sort[ $b->term_id ] )
            $res = ($sort[ $a->term_id ] > $sort[ $b->term_id ]) ? 1 : -1;
        else if( !isset( $sort[ $a->term_id ] ) && isset( $sort[ $b->term_id ] ) )
            $res = 1;
        else if( isset( $sort[ $a->term_id ] ) && !isset( $sort[ $b->term_id ] ) )
            $res = -1;
        else
            $res = 0;

        return $res;
    } );

    return $category;
}

print_r( get_sorted_categories('CUSTOM_FIELD_KEY') );

只需将自定义字段键传递给函数。