How can I use Woocommerce $product->get_attribute in functions.php? (if at all)

I am trying to use:
if ( $product->get_attribute( ‘pa_orientation’ ) == ‘vertical’) {
// do something
}

in my wordpress functions.php

The goal is to load a style sheet for products when an attribute is matched.

The code above doesn’t work. I suspect either it causes an error on non woocommerce pages where the function is not set, or my conditional is not the right type (array?). Does anyone know if $product->get_attribute can be used this way inside functions.php

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

get_attribute() is a method of the WC_Product object, so $product needs to be an instance of WC_Product that represents the current product. Your code on its own won’t work because $product is likely not defined.

So you need to define $product, but you also need to determine which product it should be defined as. In your case it needs to be the current product when viewing a single product page. You can do this by:

  1. Determining if you’re on a single product page.
  2. If you are, get a WC_Product instance of the product that the page is for.

For #1, use is_product(), and for #2 use get_queried_object() to get a post object for that product, combined with wc_get_product() to get the WC_Product object for that product.

Altogether that looks like this:

add_action(
    'wp_enqueue_scripts',
    function() {
        if ( function_exists( 'is_product' ) && is_product() ) {
            $post    = get_queried_object();
            $product = wc_get_product( $post );

            if ( 'vertical' === $product->get_attribute( 'pa_orientation' ) ) {
                // Enqueue your stylesheet.
            }
        }
    }
);

Note that I added a check for function_exists( 'is_product' ). The is_product() function is a WooCommerce function, so your site would crash if WooCommerce was deactivated. Checking for the function before using it prevents that.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x