0

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

Here is the query:

<?php
$temp = $wp_query; 
$wp_query = null;  
$wp_query = new WP_Query(); 
$wp_query->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')); ?>
</div>

<?php 
$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:

["query"]=>
  array(6) {
    ["showposts"]=>
    string(2) "12"
    ["order"]=>
    string(4) "DESC"
    ["orderby"]=>
    string(14) "meta_value_num"
    ["meta_key"]=>
    string(19) "cv_post_views_count"
    ["post_type"]=>
    string(4) "post"
    ["paged"]=>
    string(1) "0"
  }

Generated SQL Query:

SELECT SQL_CALC_FOUND_ROWS cvr_posts.ID
FROM cvr_posts
INNER JOIN cvr_postmeta ON (cvr_posts.ID = cvr_postmeta.post_id)
WHERE 1=1
  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.