0

I'm trying to get the most voted posts from last month, last week and last day. All seems to work right except the "top week". Here is the code:

<?php

//Date for ranking
$today = getdate();

if(is_page( 'topdia' )) {
    $date_query = array(array(
                            'year'  => $today["year"],
                            'month' => $today["mon"],
                            'day'   => $today["mday"],
                            )); 

    $date = new DateTime();
    $date = $date->format('Y-m-d H:i:s');
}
elseif(is_page( 'topsemana' )) { 
    $date_query = array(array(
                                    'year' => date('Y'),
                                    'week' => date('W'),
                                ));
    $date = new DateTime('-1 week');
    $date = $date->format('Y-m-d H:i:s');
}
elseif(is_page( 'topmes' )) {
    $date_query = array(array(
                                        'column' => 'post_date_gmt',
                                        'after' => '1 month ago',
                                    ));

    $date = new DateTime('-1 month');
    $date = $date->format('Y-m-d H:i:s');                                   
}
else {
    $date_query = 'any';                                                
    $date = '0000-00-00 00:00:00';
}
//Seleccionar los más votados
global $wpdb;

$query = "SELECT 
  p.id AS id, 
  SUM(v.value) AS votes
FROM 
  {$wpdb->posts} p 
INNER JOIN nsn_wti_like_post v ON v.post_id = p.id
WHERE p.post_date >= '{$date}'
GROUP BY
  p.id
ORDER BY
  SUM(v.value) DESC
LIMIT 5";

$myrows = $wpdb->get_results( $query );

$count = 0;
$posts_id = array();
$posts_votes = array();
foreach( $myrows as $post ) {
    if($post->votes > 0) {
        $posts_id[] = $post->id;
        $posts_votes[] = $post->votes;
    }
}

$temp = $wp_query; // assign ordinal query to temp variable for later use  
$wp_query = null;
$wp_query = new WP_Query( array( 'post__in' => $posts_id, 'ignore_sticky_posts' => true, 'date_query' => $date_query, 'orderby' => 'post__in' ) ); 
?>

And then, I call the loop:

if ($wp_query->have_posts()) : while ( $wp_query->have_posts() ) : $wp_query->the_post();

The problem is a weird result for the "top week" page. Just one post is shown and with a not corresponding number of votes. Any idea of what I'm doing wrong?

  • 3
    The WP_Query construction seems ok for me. Don't forget you're excluding posts using post__in. – vmassuchetto Apr 30 '14 at 1:57
  • Check with only the date_query passed into WP_Query as there may be other conditions affecting your result. – Chittaranjan Apr 30 '14 at 5:49
  • @vmassuchetto - You're right. I don't need 'date_query'. Thanks. – Manolo Apr 30 '14 at 10:02

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.