我正在开发一个网站,客户可以在主页上添加和编辑产品。他们可以通过高级自定义字段来实现这一点。
它工作得很好,直到我突然发现一个产品的销售价格没有显示出来。这是因为它是主要产品的变体。
我当前使用此代码检索高级客户字段和链接产品:
<?php
$post_object = get_field('product_1');
if( $post_object ):
$post = $post_object;
setup_postdata( $post );
$product_id = $post->ID;
$product = wc_get_product( $product_id );
$category = get_the_terms( $post->ID, 'product_cat' );
$category_link = get_term_link( $category[0]->term_id, 'product_cat' );
$category_id = get_term_by('id', $category[0]->term_id, 'product_cat');
$category_name = $category_id->name;
?>
<?php
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
?>
<a href="<?php the_permalink(); ?>">
<div class="badge-wrapper">
<img class="sale-badge" src="/wp-content/uploads/sale-image.png" />
<?php echo $product->get_price_html(); ?>
</div>
<img src="<?php echo $image[0]; ?>" data-id="<?php echo $post->ID; ?>">
<h6><?php the_title(); ?></h6>
</a>
<a class="more-info" href="<?php echo $category_link; ?>">View all</a>
<?php wp_reset_postdata();?>
<?php endif; ?>
我知道,也许这不是获取所有信息的最佳方式,但它是有效的。至少到现在为止。我发现并尝试了许多不同的教程,但没有一个很好地工作。我最接近这个教程:
PHP
function get_variation_price_by_id($product_id, $variation_id){
$currency_symbol = get_woocommerce_currency_symbol();
$product = new WC_Product_Variable($product_id);
$variations = $product->get_available_variations();
$var_data = [];
foreach ($variations as $variation) {
if($variation['variation_id'] == $variation_id){
$display_regular_price = $variation['display_regular_price'].'<span class="currency">'. $currency_symbol .'</span>';
$display_price = $variation['display_price'].'<span class="currency">'. $currency_symbol .'</span>';
}
}
//Check if Regular price is equal with Sale price (Display price)
if ($display_regular_price == $display_price){
$display_price = false;
}
$priceArray = array(
'display_regular_price' => $display_regular_price,
'display_price' => $display_price
);
$priceObject = (object)$priceArray;
return $priceObject;
}
使用此代码返回结果,其中“9”是post id,15是variation id:
<?php
$variation_price = get_variation_price_by_id(9, 15);
echo $variation_price -> display_regular_price;
echo $variation_price -> display_price;
?>
我已经准备好了$post->id;,但我不知道如何获取产品的变体id(post)
我怎样才能做好呢?