To get Woocommerce product variations or attributes, we would have to pass product id first and a Woocommerce hook to implement.
If we would call it before some actions have finished like ( woocommerce_init, woocommerce_after_register_taxonomy, and woocommerce_after_register_post_type ) then it would throw an error.
Find product id in woocommerce
In Woocommerce there are many ways to get a product id.
global $product;
$id = $product->get_id();
if you are in WordPress Loop then use get_the_ID()
So to get product variations by product id we have to pass it to wc_get_product function. It will return WC_Product_Variable Object.
After getting WC_Product_Variable Object you can directly call get_available_variations() method to get all available variations of a product.
To find the Woocommerce product variation_id
Using wp_list_pluck( $variations, ‘variation_id’ ) we can get a array of variation_id.
complete code below
add_action('woocommerce_after_register_post_type', 'woo_product_variation');
function woo_product_variation(){
/* global $product;
$product_id = $product->get_id(); */
/* woocommerce product object by product id */
$product_id = 12;
$product = wc_get_product($product_id);
$variations = $product->get_available_variations();
/* return variations id array */
$variations_id = wp_list_pluck( $variations, 'variation_id' );
/* return variation attributes array */
$attributes = $product->get_variation_attributes();
$attributesArray = wp_list_pluck( $variations, 'attributes' );
foreach($attributesArray as $nameOfAttribute => $valueOfAttribute) {
echo array_values($valueOfAttribute)[0];
}
}
Easy to check if post has specific category.