Jordan
Jordan

Reputation: 107

Get WooCommerce product attributes from complete order?

I am working on a small plugin for WooCommerce that will allow me to create a URL from an object to link to a certain page. That page will take into account the PHP GET variables and generate a technical drawing. In my theme's "admin-new-order.php" page, I have added the following code just above where the email's order table is generated:

$ordered_items = $order->get_items();
foreach ( $ordered_items as $item ) {
$product_name = $item['name'];
    $product_id = $item['product_id'];
    $product_variation_id = $item['variation_id'];

    if($product_id == "1388")
    {
        if ($product_variation_id) { 
        $product = wc_get_product( $item['variation_id'] );
        var_dump($product->get_attributes());
        // Get the attributes
        // Process the attributes
        // Create URL 
        // Echo URL
        }
    }

}

If I put an echo into the above then it appears in the right place of the email, so I know the code is executing as expected.

The links will be generated only by product with id "1388", which also executes as expected in testing. Product id "1388" is a variable product where the customer can select material, shape etc. and also I am using the Measurement Price Calculator plugin so the user can set their required size.

The problem lies within the line that says

echo $product->get_attributes();

When this line of code is present, I get an internal server error when trying to make an order and the order won't go through.

I am trying to get the selected attributes from out of the product so I can splice them up and generate a URL to take you to a page that will generate a technical drawing. I know it's possible because the table in the email contains the set attributes but I can't seem to find where and how WooCommerce does this.

A push in the right direction would be greatly appreciated, thank you.

EDIT: As Reigel suggested, I have amended the following code in my block:

    $product = wc_get_product( $item['variation_id'] );
    var_dump($product->get_attributes());

A var_dump of this produces this for example:

{ ["material"]=> array(6) { ["name"]=> string(8) "Material" ["value"]=> string(15) "Steel | Plastic" ["position"]=> string(1) "0" ["is_visible"]=> int(1) ["is_variation"]=> int(1) ["is_taxonomy"]=> int(0) }

As you can see, the material value is "Steel | Plastic", I chose Steel in the order here so I'd like to get that value, ie. the one the user selected

Upvotes: 2

Views: 5367

Answers (1)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

try it something like this:

$ordered_items = $order->get_items();
foreach ( $ordered_items as $item ) {
    $product = $order->get_product_from_item( $item );
    var_dump($product->get_attributes());
}

Upvotes: 3

Related Questions