Skip to content

Instantly share code, notes, and snippets.

@orangerdev
Created June 26, 2018 09:39
Show Gist options
  • Save orangerdev/882ae4c36492fedef7cf1921da8318f4 to your computer and use it in GitHub Desktop.
Save orangerdev/882ae4c36492fedef7cf1921da8318f4 to your computer and use it in GitHub Desktop.
Display variation value in variation dropdown (Woocommerce)
<?php
/**
* Plugin Name: WooCommerce - Display Variation Price in Dropdown
* Plugin URI: https://ridwanarifandi.com
* Description: Display price in variation dropdown
* Version: 1.0.0
* Author: Ridwan Arifandi
* Author URI: https://ridwanarifandi
* Text Domain: woocommerce
*
*/
// Set global variable to store the price value
global $variation_prices;
$variation_prices = [];
/**
* Check attribute price then store into global variable $variation_prices
* Hooked via filter woocommerce_dropdown_variation_attribute_options_args
* @param array $args [description]
* @return array [description]
*/
function check_variation_dropdown_args($args)
{
global $product,$variation_prices;
$attribute = $args['attribute'];
$options = $args['options'];
$variations = $product->get_available_variations();
foreach($variations as $var) :
if(isset($var['attributes']['attribute_'.$attribute]) && in_array($var['attributes']['attribute_'.$attribute],$options)) :
$size = ($var['attributes']['attribute_'.$attribute]);
$variation_prices[$size] = strip_tags($var['price_html']);
endif;
endforeach;
return $args;
}
add_filter('woocommerce_dropdown_variation_attribute_options_args','check_variation_dropdown_args');
/**
* Display variation price if exits
* @param string $label [description]
* @return string [description]
*/
function display_price_in_variation_dropdown($label)
{
global $product,$variation_prices;
$slug = sanitize_title($label);
if(isset($variation_prices[$slug])) :
$label .= " (".$variation_prices[$slug].")";
endif;
return $label;
}
add_filter('woocommerce_variation_option_name','display_price_in_variation_dropdown');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment