按ID显示WooCommerce的变化(常规或销售)价格



我正在开发一个网店,客户可以在主页上自己添加和编辑产品。他们可以通过高级自定义字段来实现这一点。

它运行良好,直到我突然注意到没有显示产品的销售价格。这是因为它是主要产品的变体。

我目前使用此代码来检索高级客户字段和链接的产品:

<?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; ?>

我知道,也许这不是获得所有信息的最佳方式,但它是有效的。至少到目前为止。我发现并尝试了许多不同的教程,但没有一个效果很好。我最接近这个教程:

functions.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"是帖子ID,15是变体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

我怎样才能以一种好的方式做到这一点?

您可以使用函数get_price_html((

$product->get_price_html()

我曾经在ajax search pro中遇到过同样的问题,我编写了一些代码,将html拆分为多个部分,这样你就可以随心所欲地进行样式设置。你可以看看你是否可以使用它:-(

<?php
$r_product = wc_get_product($r->id);
$price_html = strip_tags($r_product->get_price_html());
$pieces = explode(' ', $price_html);
if(count($pieces)) {
echo'<div class="search-result-price">';
if(count($pieces) === 3) {
$price .= '<ins>';
foreach($pieces as $piece) {
$price .= $piece . ' ';
}
$price .= '</ins>';
echo $price;
} else if(count($pieces) === 2) {
echo '<del>' . $pieces[0] . '</del>';
echo '<ins>' . $pieces[1] . '</ins>';
} else if(count($pieces) === 1) {
echo '<ins>' . $pieces[0] . '</ins>';
}
echo'</div>';
}
?>

最新更新