admin管理员组文章数量:1323524
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 badges1 Answer
Reset to default 2get_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.
本文标签: How can I use Woocommerce productgtgetattribute in functionsphp (if at all)
版权声明:本文标题:How can I use Woocommerce $product->get_attribute in functions.php? (if at all) 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742131463a2422179.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论