admin管理员组

文章数量:1323348

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

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

Share Improve this question asked Sep 7, 2020 at 17:00 AaronAaron 1052 silver badges5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

本文标签: How can I use Woocommerce productgtgetattribute in functionsphp (if at all)