Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Im trying to make my post random when i lick on my button using $_GET but it just keeps refreshing my page instead of refreshing with the random post.

    <a href="<?php echo $my_query; ?>?p=random"><img src="<?php bloginfo('template_directory'); ?>/images/shakeup.png" alt="" /></a>

<?php if(isset($_GET['p']) && $_GET['p']=='random') {?> 
<?php $my_query = new WP_Query('orderby=rand'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>

im getting this error now "Call to a member function have_posts() on a non-object in"

share|improve this question
    
use query_posts(); instead. –  Sisir Aug 15 '11 at 18:42

2 Answers 2

up vote 2 down vote accepted

You cannot use the direct class methods have_posts() or the_post() unless you're working with the main query. In order to modify the main query you must use query_posts.

If you want to create a new query object you need to call those methods from the new query object as Rarst showed in his example.

So you should be either...

  • Changing the main query

    <?php query_posts('orderby=rand'); ?>
    
    <div id="front-video-container">
    
    <?php if( have_posts() ) : ?>           
    <?php while( have_posts() ) : the_post(); ?>
    

NOTE: If this query has other purposes you may need to retain existing query parameters, using an array merge or conditional query_posts logic.

  • Or, creating a new query

    <?php $my_query = new WP_Query('orderby=rand'); ?>
    
    <div id="front-video-container">
    
    <?php if( $my_query->have_posts() ) : ?>           
    <?php while( $my_query->have_posts() ) : $my_query->the_post(); ?>
    

It's hard to say without seeing more of the code and knowing where you're placing it, i'd assume you will need to retain query parameters, in which case i'd suggest using the first sample and conditionalising the query_posts line.. eg.

<?php 
if( isset( $_GET['p'] ) && 'random' == $_GET['p'] ) {
    query_posts('orderby=rand');
}
?>

Hope that helps.

share|improve this answer

You are using new WP_Query object, but wrapper functions for main query.

Try:

<?php if ($my_query->have_posts()) : ?>           
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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