Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/db029acff6d621078e4865ada63ad88f to your computer and use it in GitHub Desktop.
Save FrancoStino/db029acff6d621078e4865ada63ad88f to your computer and use it in GitHub Desktop.
Add unitary price into select variation
<?php
/*
* Add unitary price into select variation
*/
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] );
$min_unit_price = $product->get_meta('_min_unit_price');
/*$price = wc_price( wc_get_price_to_display( $product, array( 'price' => $min_unit_price ) ) );
$price .= ' <span class="prefix" style="font-size:11px;color: #666;text-align: center;">'.__('Prezzo Unitario').'</span>';*/
return $term . ' (' . wp_kses( woocommerce_price( $_product->get_price() / $term ), array() ) . ')';
}
return $term;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment