I am trying to display prices next to variations on Woocommerce, which I could do just fine. Now instead of showing prices on ALL variations I just want to show prices next to variations belonging to a specific category.
This is what I have come up with so far and logically it makes sense, but not working on this particular category. Any suggestions on how to troubleshoot?
//get prices of variations
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$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 = $product->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] );
$itemPrice = strip_tags (woocommerce_price( $_product->get_price() ));
//this is where you can actually customize how the price is displayed
return $term . ' (' . $itemPrice . ')';
}
return $term;
//Add prices to variations
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $termItem ) $categories[] = $termItem->slug;
if ( in_array( 'custom-pet-portrait-painting', $categories ) ) {
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
} //end function
}
Or can I use get_terms to wrap the below code in which shows the variations price? I pretty much just need to show the prices for variations pertaining to one category.
if (has_term ('my-category', 'product_cat')) {
//get prices of variations
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$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 = $product->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] );
$itemPrice = strip_tags (woocommerce_price( $_product->get_price() ));
//this is where you can actually customize how the price is displayed
return $term . ' (' . $itemPrice . ')';
}
return $term;
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
} //end has_term