Search code examples
phpwordpressloopsjquery-post

Limiting posts in loop


Hi I have a loop with testimonials using advanced custom fields. I need the loop to only loop one post at a time randomly i have tried query_posts but its doest work.

<?php
                query_posts( 'posts_per_page=1&orderby=rand' );
            if(get_field('testimonials', 'options')): ?>

                <?php while(has_sub_field('testimonials', 'options')): ?>

                    <ul>
                        <li class="title"><?php the_sub_field('name'); ?></li>
                        <li class="site"><a href="<?php the_sub_field('website'); ?>" target="_blank"><?php the_sub_field('website'); ?></a></li>
                        <li class="desc"><?php the_sub_field('message'); ?></li>
                    </ul>

                <?php endwhile; ?>

            <?php endif; ?> 

Solution

  • I found the solution here :) http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/

    <?php 
    
    // args
    $args = array(
        'numberposts' => -1,
        'post_type' => 'event',
        'meta_key' => 'location',
        'meta_value' => 'Melbourne'
    );
    
    // get results
    $the_query = new WP_Query( $args );
    
    // The Loop
    ?>
    <?php if( $the_query->have_posts() ): ?>
        <ul>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li>
                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
            </li>
        <?php endwhile; ?>
        </ul>
    <?php endif; ?>
    
    <?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>