Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Last active November 16, 2020 23:48
Show Gist options
  • Save trvswgnr/ef8f24c78a52374ab682f1e0da7b913f to your computer and use it in GitHub Desktop.
Save trvswgnr/ef8f24c78a52374ab682f1e0da7b913f to your computer and use it in GitHub Desktop.
Display price in variation option dropdown for products that have only one attribute.
<?php
/**
* Display price in variation options dropdown for products that have only one attribute.
*
* @author Travis Aaron Wagner <[email protected]>
* @param string $term Existing option term value.
* @return string $term Existing option term value or updated term value with price.
*/
function display_price_in_variation_options( $term ) {
$product = wc_get_product();
$id = $product->get_id();
if ( empty( $term ) || empty( $id ) ) {
return $term;
}
if ( $product->is_type( 'variable' ) ) {
$product_variations = $product->get_available_variations();
} else {
return $term;
}
foreach ( $product_variations as $variation ) {
if ( count( $variation['attributes'] ) > 1 ) {
return $term;
}
$attribute = array_values( $variation['attributes'] )[0];
if ( $attribute === $term ) {
$term .= ' (' . wp_strip_all_tags( wc_price( $variation['display_price'] ) ) . ')';
}
}
return $term;
}
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_options' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment