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:
- Determining if you’re on a single product page.
- 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.