如何获得所选变量产品的有效价格

时间:2014-11-18 09:23:15

标签: woocommerce

我正在尝试访问所选产品的产品价格,以便我可以在我的PHP代码中使用它来进行一些计算。我找到了一个只能部分工作的代码。代码仅显示第一个变量产品的价格。当我在代码行中将值从0更改为1时,它将显示第二个变体的价格。 $ availablevariations [0] [' variation_id&#39]。 我试图根据从下拉列表中选择的任何选项获得产品的当前价格。 这是我正在使用的代码,它不按照我希望的方式工作

    // Get current product variation price
    global $product;

    //get the sale price of the product whether it be simple, grouped or variable
    echo $saleprice = getpostmeta( gettheID(), '_price', true);

    //get the regular price of the product, but of a simple product
    $regular_price = get_post_meta( get_the_ID(), '_regular_price', true);

    //oh, the product is variable to $sale_price is empty? Lets get a variation price

    if ($regular_price == ""){
    #Step 1: Get product varations
    $available_variations = $product->get_available_variations();

    #Step 2: Get product variation id
    $variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation.

    #Step 3: Create the variable product object
    $variable_product1= new WC_Product_Variation( $variation_id );

    #Step 4: You have the data. Have fun :)
    $regular_price = $variable_product1 ->regular_price;

}

        echo "<br> $regular_price ---This is the price I am trying to fix "

我需要使用此代码对当前变量产品价格进行一些操作,因此如果您想查看,链接为http://www.emotionadv.it/shop/volantini/volantino/,当我更改属性时,价格会发生变化。 我想在下表中使用该价格。

2 个答案:

答案 0 :(得分:0)

WooCommerce有一个自定义触发器,可在发现变体时触发。如果找到变体,则会运行以下内容...并在控制台中转储variation变量,以便您可以查看可用的内容。

jQuery( document ).ready( function($) {

    $( '.variations_form' ).each( function() {

        // when variation is found, do something
        $(this).on( 'found_variation', function( event, variation ) {
            console.log(variation);
        });

    });

} );

variation应该是这样的:

有两种变体对您有用。

variation.price_html = "<span class="price"><span class="amount">$40.00</span></span>";

您可以从此字符串中提取价格。如果没有,那么您可以使用ajax使用variation.variation_id从产品对象返回数字价格。

$product = wc_get_product($variation_id);
$price = $product->get_price();

答案 1 :(得分:0)

我已经用你的jQuery代码创建了一个单独的脚本,我加载它的文件的名字是&#34; prova&#34;,但现在我不知道如何捕获变量价格,我尝试使用$ product = wc_get_product($ variation_id); $ price = $ product-&gt; get_price();我把这段代码放在wp_enqueue_script之后(&#39; prova&#39;);但是$ price是变量产品的最低价格。

相关问题