2

I want to show posts using WP_Query functions. Also I want to add random order.

So I try

<?php
  $temp = $wp_query; 
  $wp_query= null;
  $args = array(
        'orderby' => 'rand',
  ); 
  $wp_query = new WP_Query($args);
  $wp_query->query('showposts=8' . '&paged='.$paged );
  while ($wp_query->have_posts()) : $wp_query->the_post();
?>

I can see 8 posts but it seems 'orderby' => 'rand' doesn't work.

3

It's quite some time since I worked with WordPress, but it seems to me that:

You're executing the query twice.

  • First when you pass $args to the constructor during instantiation.

  • Second when you call query().

With this, you're essentially overwriting the first query (the one that contains the orderby=rand).

The documentation of WP_Query mentions that get_posts() is called if you use a parameter in the constructor, and it shouldn't be called twice:

&get_posts() – Fetch and return the requested posts from the database. Also populate $posts and $post_count. Note: This is called during construction if WP_Query is constructed with arguments. It is not idempotent and should not be called more than once on the same query object. Doing so may result in a broken query.

And the query() method's documentation states that it calls get_posts(), therefore it's called twice:

&query( $query )Call parse_query() and get_posts(). Return the results of get_posts().

The solution:

  • You should either put everything in $args, or
  • add the orderby parameter too to the $wp_query->query(..) call.
| improve this answer | |
1

Take a look at the WP_Query class reference and work yourself up from there. Try the basic examples, play around with the parameters until you get a feel for how WP_Query and the loop works.

https://codex.wordpress.org/Class_Reference/WP_Query

The reason your query isn't working is that you are not passing the parameters correctly (use the args array for all) and using deprecated params.

| improve this answer | |

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.