so I got a working shortcode that outputs the selected product attribute name and id alongside, however, I have no idea how to obtain the same product variable name and id which is essentially from the same attribute.
This means that my current product form URL slug cannot add to cart the selected variable e.g. ( ?add-to-cart=18395&quantity=1&?variation_id=407 ) because the variation id is fetched from the attribute, and it is wrong I know.
add_shortcode ('color_attribute', function (){
$color_attributes = get_the_terms($post->ID, 'pa_pla_color', array(
'hide_empty' => false,
));
foreach ($color_attributes as $k => $color_attribute):
if( $k > 0 ) echo "\n";
echo $color_attribute->name . ' | ' . $color_attribute->term_id;
endforeach;
} );
Any help is really appreciated!
CodePudding user response:
Check this out
add_shortcode ('color_attribute', function (){
$color_attributes = get_the_terms($post->ID, 'pa_pla_color', array(
'hide_empty' => false,
));
$product = wc_get_product( $post->ID );
echo $product->get_name();
// Get Product Variations and Attributes
$product->get_children(); // get variations
$product->get_attributes();
$product->get_default_attributes();
$product->get_attribute( 'attributeid' ); //get specific attribute value
foreach ($color_attributes as $k => $color_attribute):
if( $k > 0 ) echo "\n";
echo $color_attribute->name . ' | ' . $color_attribute->term_id;
endforeach;
});
CodePudding user response:
For anyone else looking for similar solutions, this is how I achieved to solve my problem:
add_shortcode ('color_attribute', function (){
$color_attributes = get_the_terms($post->ID, 'pa_pla_color', array(
'hide_empty' => false,
));
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => get_the_ID() // get parent post-ID
);
$variations = get_posts( $args );
foreach ( $variations as $variation ) {
if( $variation_ID > 0 ) echo "\n";
// get variation ID
$variation_ID = $variation->ID;
$product_variation = new WC_Product_Variation( $variation_ID );
$variation_attribute = $product_variation->get_attribute('pa_pla_color');
echo $variation_attribute . ' | ' . $variation_ID;
};
});