1

I need to get 15 posts. If there are any with a tag featured, I want them to be first. If there are none, I want the rest to be random posts.

My idea was to sort posts based on a condition tag=featured DESC and randomly. Can I do that using query_posts()?

My unsuccessful attempt:

query_posts('posts_per_page=15&orderby=((tag=featured),rand)&order=desc';

Thank you.

2
  • 1
    Regardless of the answer to this question, you should never use query_posts, and you should pass in your query arguments using an array if you want anything other than the most basic/trivial queries. Consider the pre_get_posts filter or WP_Query instead
    – Tom J Nowell
    Nov 15, 2014 at 20:54
  • I'm not currently in the position to code, but you'll need to get 15 random posts regardless. The kind of sorting you are after is not available in Wordpress. You will need to sort the returned array of $posts with usort. Have a look at this post. This should get you there Nov 16, 2014 at 5:45

1 Answer 1

1

As Tom said, you should never use query_posts and should almost always pass any arguments as an array.

I think this will achieve what you want:

<?php

    // Arguments
    $args = array('
        'nopaging'          => true,
        'terms'             => 'featured',
        'posts_per_page'    => 15,
        'orderby'           => 'rand',
        'order'             => 'DESC',
    ');

    // The query
    $the_query = new WP_Query( $args );

    // The loop
    if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) {
            $the_query->the_post();

            /*
                Output here, e.g.
                echo '<h2>' . get_the_title() . '</h2>';
                echo '<div>' . get_the_content() . '</div>';
            */

        }
    }

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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