31

I am creating a woocommerce theme and I have product variations i.e. size which is displayed on product details page but problem is that I want to get all variations in my custom php page by using product id, can any one help me.

Thanks in advance.

Sachin Magar
  • 411
  • 1
  • 6
  • 3

5 Answers5

52

You can use: $available_variations = $product->get_available_variations();

If this is a single style template, make sure you add global $product; near the top.

From there, you can foreach through the variations and do as you wish... since you didn't have any specific output I hope that this sets you on the right track.

Shawn Wernig
  • 1,742
  • 14
  • 18
  • 9
    Be noted than in some cases you can get a 'Call to undefined method' fatal error, so better check whether you are calling a method on a correct object (a WC_Product_Variable and not a WC_Product_Simple), like this: if ($product->product_type == 'variable') ... – Eugene Sue Sep 22 '15 at 14:37
  • 1
    @EugeneSue Note that as of WC 3.0 you will get the following error `Notice: product_type was called incorrectly. Product properties should not be accessed directly.`, The answer from @Deveoo is the correct way to run the check now – cameronjonesweb May 17 '17 at 00:33
34

You can use the code below:

global $woocommerce, $product, $post;
// test if product is variable
if ($product->is_type( 'variable' )) 
{
    $available_variations = $product->get_available_variations();
    foreach ($available_variations as $key => $value) 
    { 
        //get values HERE  
    }
}
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Deveoo
  • 463
  • 4
  • 11
  • Hi @Deveoo.... I have a custom product type called bundle... I enabled variations using https://stackoverflow.com/questions/42835590/how-to-add-variations-tab-in-custom-product-type-in-woocommerce.... Now I want to display them on frontend too... Do you have any idea how to do it? I am receiving 'Call to undefined method' fatal error (The first comment on most votes answer in this question) – I am the Most Stupid Person Nov 02 '18 at 03:33
  • Hi , I find this tutorial , I think that it can help you : https://jeroensormani.com/adding-a-custom-woocommerce-product-type/ – Deveoo Nov 05 '18 at 11:02
  • get_available_variations() returns empty or null in the template. but on backend all variation values loads as expected. Any help? – Assad Nazar Jul 09 '20 at 14:53
  • Hi, did you add "global $woocommerce;" before using "get_available_variations() "function ? – Deveoo Jul 17 '20 at 09:52
11

The following code:

$variations = $product->get_available_variations();

will return all variantion of product

This function is put where you show all variation:

\wp-content\plugins\woocommerce\templates\single-product\add-to-cart\variable.php
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Sp.
  • 136
  • 1
  • 5
  • get_available_variations() returns empty or null in the template. but on backend all variation values loads as expected. Any help? – Assad Nazar Jul 09 '20 at 14:52
2

A common problem often starts from changing "In stock" or "Out of stock" labels for a single product. There are few solutions out there, where you need to change functions.php file and add a new filter.

The problems get more complicated when you need to modify this for product variations.

This may be your solution: http://bucketpress.com/changing-stock-availability-text-for-product-variations

In order to display available variations of the product you need to modify variable.php file, which can be found in /wp-content/plugins/woocommerce/templates/single-product/add-to-cart/

Find this:

<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->id ); ?>" data-product_variations="<?php echo htmlspecialchars( json_encode( $available_variations ) ) ?>">

and before tag paste this code:

foreach( $available_variations as $i => $variation ) {
//check if variation has stock or not 
if ( $variation['is_in_stock'] ) {
    // Get max qty that user can purchase
    $max_qty = $variation['max_qty'];

    // Prepare availability html for stock available instance
    $availability_html = '<p class="stock in-stock">' . $max_qty . ' units available for your purchase.' . '</p>';
} else {
    // Prepare availability html for out of stock instance
    $availability_html = '<p class="stock out-of-stock">Oops, we have no stock left.</p>';
}
$available_variations[$i]['availability_html'] = $availability_html; }

Don't forget to move php end tag "?>" from this line

do_action( 'woocommerce_before_add_to_cart_form' ); ?>

after your new code.

So the complete variable.php file should like something like this (WooCommerce 3.2.4):

<?php
/**
 * Variable product add to cart
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/single-product/add-to-cart/variable.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 3.0.0
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

global $product;

$attribute_keys = array_keys( $attributes );

do_action( 'woocommerce_before_add_to_cart_form' ); 

// Your New Code goes here:
foreach( $available_variations as $i => $variation ) {
    // check if variation has stock or not 
    if ( $variation['is_in_stock'] ) {
        // Get max qty that user can purchase
        $max_qty = $variation['max_qty'];

        // Prepare availability html for stock available instance
        $availability_html = '<p class="stock in-stock">Available: ' . $max_qty . '</p>';
    } else {
        // Prepare availability html for out of stock instance
        $availability_html = '<p class="stock out-of-stock">Out of stock!</p>';
    }
    $available_variations[$i]['availability_html'] = $availability_html;
} ?>

<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
    <?php do_action( 'woocommerce_before_variations_form' ); ?>

    <?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
        <p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
    <?php else : ?>
        <table class="variations" cellspacing="0">
            <tbody>
                <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                    <tr>
                        <td class="label"><label for="<?php echo sanitize_title( $attribute_name ); ?>"><?php echo wc_attribute_label( $attribute_name ); ?></label></td>
                        <td class="value">
                            <?php
                                $selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
                                wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
                                echo end( $attribute_keys ) === $attribute_name ? apply_filters( 'woocommerce_reset_variations_link', '<a class="reset_variations" href="#">' . esc_html__( 'Clear', 'woocommerce' ) . '</a>' ) : '';
                            ?>
                        </td>
                    </tr>
                <?php endforeach;?>
            </tbody>
        </table>

        <?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>

        <div class="single_variation_wrap">
            <?php
                /**
                 * woocommerce_before_single_variation Hook.
                 */
                do_action( 'woocommerce_before_single_variation' );

                /**
                 * woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
                 * @since 2.4.0
                 * @hooked woocommerce_single_variation - 10 Empty div for variation data.
                 * @hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
                 */
                do_action( 'woocommerce_single_variation' );

                /**
                 * woocommerce_after_single_variation Hook.
                 */
                do_action( 'woocommerce_after_single_variation' );
            ?>
        </div>

        <?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
    <?php endif; ?>

    <?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>

<?php
do_action( 'woocommerce_after_add_to_cart_form' );

All credits to "Kevin" from: http://bucketpress.com/author/base-admin

jankowskit
  • 21
  • 1
  • A solution as a filter (not needing to override the template files): ``` add_filter( 'woocommerce_available_variation', function($variation) { if ( $variation['is_in_stock'] ) { $availability_html = 'In stock'; } else { $availability_html = 'Out of stock'; } $variation['availability_html'] = $availability_html; return $variation; }); ``` – Luuk Skeur Jul 22 '19 at 08:17
0

Try this,

<?php
$name_size = get_post_meta($_GET['pr_id'],'product_size', true);
$t_shirt_sizes_array = wp_get_post_terms($_GET['pr_id'],'pa_size');
$t_shirt_size = array();
$t_shirt_price = array();
for($scnt = 0; $scnt < count($t_shirt_sizes_array); $scnt++){
$t_shirt_size[] = $t_shirt_sizes_array[$scnt]->name;
$t_shirt_price[] = $t_shirt_sizes_array[$scnt]->slug;
$t_shirt_size_id[] = $t_shirt_sizes_array[$scnt]->term_id;
}
$cnt = 1;
for($i = 0; $i < count($t_shirt_size); $i++){
$name_size = $t_shirt_size[$i];

$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = 
'".$t_shirt_size[$i]."'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
 $query = "SELECT postmeta.post_id AS product_id
    FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
    WHERE postmeta.meta_key LIKE 'attribute_%'
        AND postmeta.meta_value = '$term_slug'
        AND products.post_parent = ".$_GET['pr_id'];    
$variation_id = $wpdb->get_col( $query );

$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {                    
    echo $name_size;
    $_product = new WC_Product_Variation( $variation_id[0] );
    echo $_product->get_price();
}
$price = $t_shirt_price[$i];
$cnt++;
}
?>
Andro Selva
  • 53,910
  • 52
  • 193
  • 240
Dharma
  • 17
  • 2