Jess McKenzie
Jess McKenzie

Reputation: 8385

Changing Loop to include a $var

In the code below it has a foreach what would be the best way to alter it so it allows me to check $instock. I have tried using the if statement within the foreach but then it doesn't see the endforeach

Loop:

$args = array( 'posts_per_page' => 4, 'post_type' => 'product','meta_key' => '_featured','meta_value' => 'yes','orderby' =>'rand','order' => 'DESC');

$myposts = get_posts( $args );

foreach ( $myposts as $post ) : 
    setup_postdata( $post );
    $product = new WC_Product( get_the_ID() );
    $price = $product->price;
    $instock = $product->is_in_stock();
?>
    <div class="col-sm-6 col-md-3">
        <div class="thumbnail Product_Box">
            <a href="<?php the_permalink()?>"><?php the_post_thumbnail();?></a>
            <div class="caption">
                <h4><?php the_title()?><br />
                    <span class="text-color">$<?php echo $price; ?></span>
                </h4>
            </div>
        </div>
    </div>

<?php endforeach;
wp_reset_postdata();?>

Upvotes: 0

Views: 63

Answers (1)

Edwin
Edwin

Reputation: 1125

A clean solution would be to skip the product if it's not in stock. Thus what you would get is the following.

$args = array( 'posts_per_page' => 4, 'post_type' => 'product','meta_key' => '_featured','meta_value' => 'yes','orderby' =>'rand','order' => 'DESC');

$myposts = get_posts( $args );

foreach ( $myposts as $post ) : 
    setup_postdata( $post );
    $product = new WC_Product( get_the_ID() );
    $price = $product->price;
    $instock = $product->is_in_stock();

    if (!$instock) {
        continue;
    }
?>
    <div class="col-sm-6 col-md-3">
        <div class="thumbnail Product_Box">
            <a href="<?php the_permalink()?>"><?php the_post_thumbnail();?></a>
            <div class="caption">
                <h4><?php the_title()?><br />
                    <span class="text-color">$<?php echo $price; ?></span>
                </h4>
            </div>
        </div>
    </div>

<?php endforeach;
wp_reset_postdata();?>

Upvotes: 1

Related Questions