Brian Duncan
Brian Duncan

Reputation: 135

Get the product variations skus from a variable product in WooCommerce

I am trying to get an array of skus from variable products in woocommerce. Each variation has its own sku, and I have also set an overall sku for the product that encompasses all variations (in the inventory tab)

So for simple products this code works:

global $product;
$product_sku = $product->get_sku();

But when I am working with a variable product, it returns the sku listed in the Inventory tab, rather than any skus for the variations. So what would be a good way to get those variation skus in an array?

Here is some psuedo code for how I am thinking about the process

$inventory_sku = 'sku1';
$variation_skus = get_skus_by_inv_sku($inventory_sku);
echo $variation_skus[0]; 

Thanks in advance!

Upvotes: 0

Views: 5313

Answers (2)

askepott
askepott

Reputation: 279

A better option would be to instantiate the correct object by using one of the built in classes:

$product = new WC_Product_Simple($product_id)
$product = new WC_Product_Variation($variation_id)
$product = new WC_Product_Grouped($grouped_id)
$product = new WC_Product_External($external_id)

And calling the get_sku() method from it directly:

$product->get_sku();

Upvotes: -1

LoicTheAztec
LoicTheAztec

Reputation: 253784

The shortest and lightest way is to use WPDB Class to make an SQL query embedded in a function:

function get_variations_skus( $product_id ){
    global $wpdb;

    return $wpdb->get_col("
        SELECT pm.meta_value
        FROM {$wpdb->prefix}postmeta as pm
        INNER JOIN {$wpdb->prefix}posts as p ON p.ID = pm.post_id
        WHERE p.post_type = 'product_variation'
        AND p.post_status = 'publish'
        AND p.post_parent = $product_id
        AND pm.meta_key = '_sku'
        AND pm.meta_value != ''
    ");
}

Code goes in function.php file of your active child theme (or active theme) or in a plugin. Tested and works.

USAGE - In a variable product:

global $product;

// Variable product main sku
$sku = $product->get_sku();

// The variations skus for this variable product (in an array)
$variations_skus = get_variations_skus( $product->get_id() );

// Testing output variations skus:  Array to string conversion (coma separated skus)
echo sizeof($variations_skus) > 0 ? implode( ', ', $variations_skus ) : 'No skus';

Upvotes: 3

Related Questions