I have created a page where I am sorting the post according to the views.

Here is the query:

$temp = $wp_query; 
$wp_query = null;  
$wp_query = new WP_Query(); 
   'showposts' => 12,
   'order'     => 'DESC',
   'orderby'   => 'meta_value_num',
   'meta_key'  => 'cv_post_views_count',
   'post_type' => 'post',
   'paged'     => $paged,
while ($wp_query->have_posts()) : $wp_query->the_post(); 

Post Html and content goes here

<div class="post-nav-container">
    <?php previous_posts_link( __('&rarr; Older Posts','circoviral')); ?>
    <?php next_posts_link( __('&larr; Older Posts','circoviral')); ?>

$wp_query = null; 
$wp_query = $temp;  // Reset

This is a page template and I need pagination for this page because this page is having infinite scroll.

But when I see the output of the query on the pages, it is not returning the posts in the manner I requested. Only the sorting is not working.

When I debug the $wp_query, I got this:

  array(6) {
    string(2) "12"
    string(4) "DESC"
    string(14) "meta_value_num"
    string(19) "cv_post_views_count"
    string(4) "post"
    string(1) "0"

Generated SQL Query:

FROM cvr_posts
INNER JOIN cvr_postmeta ON (cvr_posts.ID = cvr_postmeta.post_id)
  AND cvr_posts.post_type = 'post'
  AND (cvr_posts.post_status = 'publish'
       OR cvr_posts.post_status = 'private')
  AND (cvr_postmeta.meta_key = 'cv_post_views_count')
GROUP BY cvr_posts.ID
ORDER BY cvr_postmeta.meta_value DESC LIMIT 0, 12

Date Range Filter

function date_range_filter($where = '') {
  $range_bottom = " AND post_date >= '".date("Y-m-d", strtotime('-1 hours') );
  $range_top = "' AND post_date <= '".date("Y-m-d")."'";

  $where .= $range_bottom . $range_top;
  return $where;
  • Had you looked at generated SQL for the query? Are you confident all of the post have custom field and proper value in it? – Rarst Dec 30 '14 at 15:07
  • Yes i looked up the generated sql query and every post have this custom field if it doesn't have it it set to zero – Harman Preet Dec 30 '14 at 16:55
  • Ok, what is generated SQL query? :) – Rarst Dec 30 '14 at 17:02
  • Generated query added to the Question @Rarst – Harman Preet Jan 2 '15 at 12:25
  • Your code works fine on my side. You most probably have some kind of filter like pre_get_posts that alters your query somehow, or even a custom query that is not properly reset – Pieter Goosen Jan 2 '15 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.