2017-07-14 74 views

回答

0

試試下面的代碼:

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')); 

只是通過自定義字段關鍵作用。

相關問題