在WooCommerce变体旁边显示价格

时间:2018-08-06 14:35:11

标签: woocommerce

我正在使用以下代码在WooCommerce的版本旁边显示价格。如果超过2个变体,效果很好,但如果只有2个变体,则这两个变体仅显示第一个变体价格。

任何对此的帮助都会很棒。

function display_price_in_variation_option_name( $term ) {

    global $wpdb, $product;

if ( is_product() ) {

    if ( $product instanceof WC_Product && $product->is_type( 'variable' ) ) {

    foreach ( $product->get_available_variations() as $variation ) {
    //$product_variation_id = $variation['variation_id'];
        foreach ( $variation['attributes'] as $variation_attribute_name => $variation_attribute_value ) {
        $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE slug = '$variation_attribute_value'" );
        if ( $term != $variation_attribute_value && $variation_attribute_value != $result[0] ) continue;
        $product_price = wc_price( $variation['display_price'] );
        $product_price = strip_tags( $product_price );
        return $term . ' - (' . $product_price . ')';
                }

    }

    }

}
    return $term;

}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );

1 个答案:

答案 0 :(得分:0)

此代码已经过测试,可与多个下拉列表,多个属性以及特定于产品的属性(例如attribute1 | attribute2 | attribute3。

//在WooCommerce的变体旁边添加价格 add_filter('woocommerce_variation_option_name','display_price_in_variation_option_names'); 函数display_price_in_variation_option_names($ term_name){

global $wpdb, $product;

if ( is_product() && $product instanceof WC_Product && $product->is_type( 'variable' ) ) {

        foreach ( $product->get_available_variations() as $variation ) {
            foreach ( $variation['attributes'] as $variation_attribute_name => $variation_attribute_value ) {
                $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE slug = '$variation_attribute_value'" );
                $taxonomy = str_replace( 'attribute_', '', $variation_attribute_name );
                $term     = get_term_by( 'slug', $variation_attribute_value, $taxonomy );
                if ( $term_name == $variation_attribute_value ) {
                $product_price = wc_price( $variation['display_price'] );
                $product_price = strip_tags( $product_price );
                return $term_name . ' - (' . $product_price . ')';
                } else if( is_object($term) && $term->name == $term_name ) {
                $product_price = wc_price( $variation['display_price'] );
                $product_price = strip_tags( $product_price );
                return $term_name . ' - (' . $product_price . ')';
                }
            }

        }

    }
return $term_name; 

}