TransWikia.com

Moving the array pointer inside a WP_Query while loop

WordPress Development Asked by Anthony Atang on November 17, 2021

How can I move the pointer ahead a place, or at least offset it, as I’m trying to pull two posts during each loop of the while loop? I’ve indicated where in the loop I would like to move the pointer:

$num_featured_max = 8;
$meta_query   = WC()->query->get_meta_query();
$meta_query[] = array(
    'key'   => '_featured',
    'value' => 'yes'
);
$args = array( 
    'post_type'      => 'product', 
    'meta_query'     =>  $meta_query, 
    'orderby'        => 'date',
    'order'          => 'ASC',
    'posts_per_page' => $num_featured_max  
);
$the_query = new WP_Query( $args );
$the_query->found_posts = $num_featured;
$i = 1;
if ( $the_query->have_posts( ) )
{
    while ( $the_query->have_posts( ) )
    {
        $key  = 'featured-image';
        $the_query->the_post( );
        $id               = get_the_ID( );
        $image_id         = get_post_thumbnail_id( );
        $background_image = wp_get_attachment_url( $image_id );
        $category_id      = get_the_terms( $post->ID, 'on-draught' );
        $title            = get_the_title();
        $section_id       = strtolower( $title );
        $url              = get_post_meta($post->ID, $key, true);
        ?>
    <div class="item <?php if($i <= 1){ echo 'active';}else{ echo 'not-active'; }?>">
        <div class="row">
            <a href="<?php the_permalink(); ?>" id="men" class="col-xs-6 smooth" style="background-image:url(<?php echo $url ?>)">
                <div class="overlay">
                    <h1 class="valign"><?php echo $title;?></h1>
                </div>
            </a>

            <!-- Trying to Move the Pointer to the next one at this point -->

            <a href="<?php the_permalink(); ?>" id="women" class="col-xs-6 smooth" style="background-image:url(<?php echo $url ?>)">
                <div class="overlay">
                    <h1 class="valign"><?php echo $title; ?></h1>
                </div>
            </a>
        </div>
    </div>  
        <?php
        $i++;
    }
}

Any thoughts? I’ve tried using ->nextpost(), but that didn’t work and is even depreciated.

Just in case, here is my website; I’m working on the slider at the top.

One Answer

$the_query->the_post() is what increments the counter and loads the next post's data.

You can also explicitly set the internal counter to an arbitrary number and begin incrementing from there...

$the_query->current_post = 3;
$the_query->the_post();
the_title(); // this will output the 4th post's title

Answered by Milo on November 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP