Woocommerce 获得变化的产品价格
问题描述:
我正在尝试在变体下拉菜单中显示产品变体价格.当您在下拉列表中选择一个变体时,我试图更改价格显示在 div 内的默认行为.
Im trying to display the product variation price inside the variations dropdown. Im trying to change default behavior where price is displayed inside a div when you choose a variation on the dropdown.
问题是我找不到那个 div 在哪里获得变化价格.我搜索了所有 javascript 但找不到它
The problem is i cant find where that div is getting the variation price. I searched all javascript but couldnt find it
如果我使用:
add_filter('woocommerce_variation_option_name' ,'add_price_to_dropdown');
function add_price_to_dropdown($name){
global $product;
return $name.' '.$product->get_price_html();
}
我只得到所有选项的最小变动价格.我想获得每个变体的价格.有什么线索吗?
I just get min variation price for all options. I want to get the price for each variation. Any clue?
答
这是您要找的代码
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
if ( empty( $term ) ) return $term;
if ( empty( $product->id ) ) return $term;
$id = $product->get_id();
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
return $term . ' (' . wp_kses( woocommerce_price( $_product->get_price() ), array() ) . ')';
}
return $term;
}
希望这会有用.