wordpress文章按两个自定义字段组合排序


wordpress在默认情况下可以使用文章的一个自定义字段进行排序,代码如下:

  1. $args = array(
  2. 'meta_key' => 'sort',
  3. 'orderby' => 'meta_value_num', // 须 WordPress 2.8 及以上版本
  4. 'order' => DESC
  5. );
  6. $arms = array_merge($args, $wp_query->query);
  7.  
  8. query_posts($arms);
  9. while (have_posts())
  10. //循环内容
  11. endwhile;wp_reset_query();

但是有时候我们可能会碰到更加复杂的情况,需要对两个自定义字段进行组合排序,方法如下:

  1. $query = "SELECT wposts.*, wpostmeta1.*, wpostmeta2.*
  2. FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta1, $wpdb->postmeta wpostmeta2
  3. WHERE wposts.ID = wpostmeta1.post_id
  4. AND wposts.ID = wpostmeta2.post_id
  5. AND wpostmeta1.meta_key = 'date'
  6. AND wpostmeta2.meta_key = 'time'
  7. ORDER BY wpostmeta1.meta_value ASC,
  8. wpostmeta2.meta_value ASC";
  9.  
  10. $results = $wpdb->get_results($query);
  11.  
  12. foreach ( $results as $result ) {
  13. //循环内容
  14. }