0

I have a loop that shows the most popular posts with the meta_value_num. I'm trying to randomize the order of the most 5 popular items. Any idea why this code isn't working?

<?php query_posts('showposts=4&cat=-20,-54&orderby=meta_value_num&order=rand&meta_key=post_views_count&order=DESC'); ?>

<? if (have_posts()) :
    while (have_posts()) : the_post();
        echo('<a href="' . get_permalink() . '">' .ShortenText(get_the_title()). '<br></a>');
        $content = get_the_content();
        preg_match('#(<img.*?>)#', $content, $results);
        echo('<a href="' . get_permalink() . '">' . $results[1] . '</br></a>');
        ?></br><?
    endwhile;
endif;; ?>
0

You're using the order parameter incorrectly for WP_Query.

  • order (string | array) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'. An array can be used for multiple order/orderby sets.
    • 'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
    • 'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).

query_posts looks to be modifying the main query. In that case, remove 'rand' from your query args and shuffle the posts directly afterwards.

query_posts('showposts=4&cat=-20,-54&orderby=meta_value_num&meta_key=post_views_count&order=DESC');

global $posts;
shuffle($posts);

if (have_posts()) :
    //...
endif;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.