WordPress loop and custom sort order issues
-
I am currently working on a loop for my website which works just fine, however I am having trouble in customizing this further, specifically when it comes to sorting the results.
Here is my current query:
<?php $i = 1; $args = array( 'numberposts' => -1, 'posts_per_page' => 25, 'post_type' => 'cars', 'orderby' => 'meta_value_num', 'meta_key' => 'pvm_like_votes_count', 'order' => 'DESC' ); $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): ?> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php $totalUpVotes = bpvm_get_vote_counts_meta($post->ID) > 0 ? bpvm_get_vote_counts_meta($post->ID) : 'N/A'; $comments = get_comments(array( 'post_id' => $post->ID )); $ratings = array(); foreach($comments as $comment) { $rating = get_comment_meta($comment->comment_ID, 'rating', true); array_push($ratings,$rating); $avgrating = array_sum($ratings)/count($ratings); } ?>After comes my related table which spits out all the correct information sorted by pvm_like_votes_count until here is all correct. See here: https://i.stack.imgur.com/q1OZw.jpg
Total upvotes are being displayed using: $totalUpVotes and it’s sorted by ‘orderby’ => ‘meta_value_num’, ‘meta_key’ => ‘pvm_like_votes_count’ in a DESC order which is perfect!
Now I wanted to tweak this a bit and only count vote results from the last 24hours and I achieved that by doing the following:
<?php $i = 1; $args = array( 'numberposts' => -1, 'posts_per_page' => 25, 'post_type' => 'cars', 'orderby' => 'meta_value_num', 'meta_key' => 'pvm_like_votes_count', 'order' => 'DESC' ); $the_query = new WP_Query( $args ); ?> <?php if( $the_query->have_posts() ): ?> <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php $datetime24h = strtotime('-1 day'); $datetime24h = date('Y-m-d H:i:s',$datetime24h); $votes = $wpdb->get_results('select * from toptr_bpvm_data where post_type = "cars" and vote_date>="'.$datetime24h.'" and postid='.$post->ID, OBJECT ); $votescount = 0; foreach ($votes as $sv => $s) { $votescount = $votescount+$s->votes; }; $comments = get_comments(array( 'post_id' => $post->ID )); $ratings = array(); foreach($comments as $comment) { $rating = get_comment_meta($comment->comment_ID, 'rating', true); array_push($ratings,$rating); $avgrating = array_sum($ratings)/count($ratings); }Votes are being displayed by using: $votescount
The values are actually correct, however it messes up my sort order as it’s not taken the highest vote on first position, please see here: https://i.stack.imgur.com/GweSN.jpg
I reckon this will have something to do with ‘orderby’ or ‘meta_key’ however I just can’t get my head around it.
Some expert help would be truly appreciated, thank you very much!
The topic ‘WordPress loop and custom sort order issues’ is closed to new replies.