【发布时间】:2017-12-05 22:22:25
【问题描述】:
我正在尝试修改related.php,以便随机显示商店中价格在加/减100范围内的任何3种产品。
我正在使用 ACF 字段和 Woocommerce 3.2。 问题是虽然选择了正确的产品,但没有显示它们的价格。而是显示所有 3 种产品的参考产品的价格。
这是代码(price_obj 是价格的 ACF 字段):
global $product, $woocommerce_loop;
$product = new WC_Product(get_the_ID());
$price_product = get_field('price_obj',get_the_ID());
$args1=array(
'post_type' => 'product',
'posts_per_page' => -1,
'post__not_in' => array( $product->get_id() )
);
$products_in_range = array();
$my_query = new wp_query($args1);
if( $my_query->have_posts() ) {
$val = count($my_query->get_posts());
while ($my_query->have_posts()) {
$my_query->the_post();
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
$price = get_field('price_obj');
$id = get_the_ID();
if ((($price_product-100) <= $price) && ($price <= ($price_product+100))){
array_push($products_in_range,$id);
}
}
}
wp_reset_query();
$rand_products = array_rand($products_in_range, 3);
?>
<?php if ($rand_products){ ?>
<div class="related products">
<h2><?php _e( 'Related Products', 'woocommerce' ); ?></h2>
<ul class="products">
<?php
foreach ($rand_products as $prod){
$title = get_the_title($products_in_range[$prod]);
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($products_in_range[$prod]), 'large');
$link = get_permalink($products_in_range[$prod]);
$product_prod = new WC_Product($products_in_range[$prod]);
$price = wc_price($product->get_price());
?>
<li class="product type-product status-publish has-post-thumbnail first instock shipping-taxable purchasable product-type-simple">
<a href="<?php echo $link; ?>" class="woocommerce-LoopProduct-link">
<span class="et_shop_image">
<img width="400" height="400"
src="<?php echo $featured_image[0]; ?>"
class="attachment-shop_catalog size-shop_catalog wp-post-image"
alt=""
title="">
<span class="et_overlay"></span>
</span>
<h3><?php echo $title; ?></h3>
<span class="price">
<span class="woocommerce-Price-amount amount">
<?php echo $price; ?>
</span>
</span>
</a>
</li>
<?php } ?>
</ul>
</div>
非常感谢您的帮助!
【问题讨论】:
-
get_filed() 可以采用三个参数。字段的 id、post id 和格式值,只需将 post id 添加到调用中,就像这样,$price = get_field('price_obj', get_the_ID());或者如果你先得到 id 那么你可以使用 get_field('price_obj', $id );
标签: woocommerce advanced-custom-fields