簡體   English   中英

獲取與WooCommerce中的默認屬性值相關的產品變體

[英]Get the Product Variation related to default attribute values in WooCommerce

我想在我的前端模板文件中顯示默認的產品屬性表單值和常規價格。

下面的var_dump顯示了數組中的選項。 我需要獲取[default_attributes]值。

<?php 
    global $product;
    echo var_dump( $product );
// Need to get the [default_attributes] values


?>

在此輸入圖像描述

要獲取變量產品的默認屬性,可以使用WC_Product方法get_default_attributes()

<?php 
    global $product;

    if( $product->is_type('variable') ){
        $default_attributes = $product->get_default_attributes();

        // Testing raw output
        var_dump($default_attributes);
    }
?>

現在要找出這個“默認”屬性的相應產品變體,有點復雜:

<?php 
    global $product;

    if( $product->is_type('variable') ){
        $default_attributes = $product->get_default_attributes();
        foreach($product->get_available_variations() as $variation_values ){
            foreach($variation_values['attributes'] as $key => $attribute_value ){
                $attribute_name = str_replace( 'attribute_', '', $key );
                $default_value = $product->get_variation_default_attribute($attribute_name);
                if( $default_value == $attribute_value ){
                    $is_default_variation = true;
                } else {
                    $is_default_variation = false;
                    break; // Stop this loop to start next main lopp
                }
            }
            if( $is_default_variation ){
                $variation_id = $variation_values['variation_id'];
                break; // Stop the main loop
            }
        }

        // Now we get the default variation data
        if( $is_default_variation ){
            // Raw output of available "default" variation details data
            echo '<pre>'; print_r($variation_values); echo '</pre>';

            // Get the "default" WC_Product_Variation object to use available methods
            $default_variation = wc_get_product($variation_id);

            // Get The active price
            $price = $default_variation->get_price(); 
        }
    }
?>

這是經過測試和運作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM