thomasmalley
thomasmalley

Reputation: 60

WooCommerce set product dimensions (width & height) based on single attribute

The Shop is selling framed images. The customer can chose frame material and dimensions (list of preset Width x Height combinations). Both – frame material and dimensions are configured as predefined Attribute Lists. For Dimensions only some very specific Width x Height combinations are available. See Example:

Example Attribute Lists

Then the option Create variations from all attributes is used to have WooCommerce generate every possible combination of these variations. So we end up with a list like this:

Example for generated Variations

The critical Point is, that now we need the 2 standard meta fields Width & Height for every variation to be filled in some way automatically based on the selected Dimension custom Attribute. Like this:

Example of needed Functionality

So basically (no real code):

if (selected Dimensions Attribute is "30 x 20 cm") set meta $width = 30 & meta $height = 20 
if (selected Dimensions Attribute is "45 x 30 cm") set meta $width = 45 & meta $height = 30 
if (selected Dimensions Attribute is "60 x 40 cm") set meta $width = 60 & meta $height = 40 
etc.

It would be enough if this happens, when the variable product is saved/updated. The solution can be pretty simplistic, since the Attribute List for Dimensions is predefined.

I know this might be a somewhat special case, but I think the needed functionality might be of interest for others too.

Can anyone help?

Upvotes: 1

Views: 2079

Answers (1)

Kaperto
Kaperto

Reputation: 320

this following code fills the width and height when the variation is saved :

add_action("woocommerce_before_product_object_save", function ($product, $data_store) {

    if ("variation" !== $product->get_type()) {
        return;
    }


    $abmessung = $product->get_attribute("abmessung-3-2"); // use the text "60 x 40 cm"
    $parse = explode(" ", $abmessung);

    $product->set_props([
        "width" => $parse[0],
        "height" => $parse[2],
    ]);


}, 10, 2);

Upvotes: 1

Related Questions