How To Find Product Variations With Your WooCommerce Product Id

How To Find Product Variations With Your WooCommerce Product Id
148 Views

It is necessary to select a variable product in the product data in the admin side.

We would need to supply the product id first in order to obtain Woocommerce product variants or characteristics.

<?php
add_action('woocommerce_after_register_post_type', 'cxc_woo_product_variation');

function cxc_woo_product_variation(){

	query_posts(array(
		'post_type' => 'product'
	)); 

	if( have_posts() ){
		while ( have_posts() ){
			the_post();	
			$product_id = get_the_ID();
			$product = wc_get_product( $product_id );

			if( $product->is_type( 'variable' ) ){
				$cxc_variations = $product->get_available_variations();

				/* return variations id array */
				$variations_id 		= wp_list_pluck( $cxc_variations, 'variation_id' );
				/* return variation attributes array */
				$attributes 		= $product->get_variation_attributes();
				$cxc_attributes 	= wp_list_pluck( $cxc_variations, 'attributes' );
				if( !empty( $cxc_attributes ) && is_array( $cxc_attributes ) ){
					foreach( $cxc_attributes as $cxc_attribute_name => $cxc_attribute_value ) {
						if( !empty( $cxc_attribute_value ) ){
							foreach ( $cxc_attribute_value as $cxc_key => $attribute) {
								echo  "<p>".$attribute."</p>";
							}
						}
					}
				}
			}
		} 
	}
}
?>

Alternative Way

1. Get WooCommerce variations programmatically

<?php
    global $product;
    $cxc_variations = $product->get_available_variations();
?>

2. Show variations Product Single Product Page

<?php
add_action( 'woocommerce_after_add_to_cart_button', 'cxc_product_variations_price_recalculate_call_back' );

function cxc_product_variations_price_recalculate_call_back() {
	global $product;
	$cxc_attribute = $product->get_attribute( 'color' );
	$cxc_attrs = explode( ',', $cxc_attribute );

	if ( is_array( $cxc_attrs ) && ! empty( $cxc_attrs ) ) {
		foreach ( $cxc_attrs as $cxc_attr ) {
			
			if( !empty( $cxc_attr ) ){
				echo '<sapn>' . $cxc_attr . '</span>';
			}
		}
	}
}
 ?>

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.