WordPress按照分页中的自定义元发布订单

时间:2012-02-22 20:42:54

标签: php wordpress custom-fields

我通过名为“size”的自定义元值来命名我的帖子。

$querystr = "
    SELECT $wpdb->posts.* 
    FROM $wpdb->posts, $wpdb->postmeta
    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
    AND $wpdb->postmeta.meta_key = 'size'
    AND $wpdb->posts.post_status = 'publish' 
    AND $wpdb->posts.post_type = 'post'
    AND $wpdb->posts.post_date < NOW()
    ORDER BY $wpdb->postmeta.meta_value DESC
 ";

 $pageposts = $wpdb->get_results($querystr, OBJECT);

if ($pageposts):
  global $post; 
  foreach ($pageposts as $post):      
  setup_postdata($post);     
      the_title();      
  endforeach;    
endif; 

wp_pagenavi(); //creates page navigation

同时我使用WP-pagenavi插件按页面导航帖子。我每页都有10个帖子。

问题:帖子在每个页面中单独订购。如何通过所有页面按降序订购帖子?

更新:我可能找到了解决方案,但我不确定如何在我的代码中实现它

http://scribu.net/wordpress/wp-pagenavi/wpn-2-74.html

$my_query = new WP_Query( array( 'tag' => 'foo', 'paged' => get_query_var('paged') ) );

while ( $my_query->have_posts() ) : $my_query->the_post();
    the_title();
    // more stuff here
endwhile;

wp_pagenavi( array( 'query' => $my_query ) );

wp_reset_postdata();    // avoid errors further down the page

1 个答案:

答案 0 :(得分:1)

我发现了一个可以解决问题的SO帖子:

How to sort a 'query_posts' function by custom field, while limiting posts by another custom field

在那里,您会找到一个自定义类,可以扩展WP_Query并允许您按自定义字段排序查询,并包含paged查询变量。

所以步骤:

  1. class PostsOrderedByMetaQuery

  2. 之后的functions.php代码中过去
  3. 将您的查询替换为:

    // Retrieve `paged` in URL
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    
    // Make the query like in WP_Query but with our custom class
    $query = new PostsOrderedByMetaQuery(array(
      'post_type'   => 'post',
      'post_status' => 'publish',
      'paged'       => $paged,
      'orderby_meta_key' => 'size',
      'orderby_order'    => 'DESC'        
    ));
    
  4. 使用它!

    while ( $query->have_posts() ) : $query->the_post();
        the_title();
        // more stuff here
    endwhile;
    
    wp_pagenavi( array( 'query' => $query ) );
    
    wp_reset_postdata();    // avoid errors further down the page