在下面的代码中,它有一个foreach
,这是改变它的最佳方式,因此它允许我检查$instock
。我尝试在if
中使用foreach
语句,但它没有看到endforeach
循环:
$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();?>
答案 0 :(得分:1)
如果产品没有库存,清洁的解决方案就是跳过产品。因此,您将获得以下内容。
$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();?>