Set and display a custom product variation value dynamically on WooCommerce single products

<?php
global $product;

// get the parent id
echo $pid = $product->get_id();
echo '<br/>';

//echo $product = wc_get_product($product_id);
//echo $variations = $product->get_available_variations();
//echo $variations_id = wp_list_pluck( $variations, 'variation_id' );

$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 $key=>$variation ) {

// get variation ID

echo $variation_ID = $variation->ID;

// get variations meta
$product_variation = new WC_Product_Variation( $variation_ID );

//echo '<pre>';
//print_r($product_variation);
//echo '</pre>';

// get variation featured image
echo $variation_image = $product_variation->get_image();

// get variation price
echo $variation_price = $product_variation->get_price_html();

// get variation attributes
$variation_attr = $product_variation->get_variation_attributes();

echo $variation_attr['attribute_pa_colors'];

// get add to cart button
$url = '?add-to-cart='.$variation_ID; // The dynamic variation ID (URL)
echo '<a href="'.$url.'" class="button alt">Add TO Cart</a> ';

// get add to request quote button
$pageurl = get_page_link(get_option('addify_atq_page_id', true));
echo '<div class="added_quote" id="added_quote'.$variation_ID.'">Product added to Quote successfully!<br><a href="'. esc_url($pageurl) .'">View Quote</a></div>';
echo '<div style="display:block; margin-bottom:10px;"><a href="javascript:void(0)" rel="nofollow" data-product_id="'.$variation_ID.'" data-product_sku="" class="eye_afrfqbt afrfqbt button add_to_cart_button product_type_simple">Add To Shopping List</a></div>';

//get_post_meta( $variation_ID , '_text_field_date_expire', true );

echo '<br/><hr/>';
} ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>