Last active
February 6, 2024 11:24
-
-
Save diggeddy/ad3c146e64b8dad417331703f21aa4c9 to your computer and use it in GitHub Desktop.
Woocommerce add a Specific Product Attribute as a class to `post_class`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'post_class', function( $classes ) { | |
// Check if WooCommerce is active | |
if ( ! class_exists( 'WC_Product' ) ) { | |
return $classes; | |
} | |
global $post; | |
$custom_classes = array(); | |
// Check if the post type is a product | |
if ( 'product' === get_post_type( $post ) ) { | |
$product = wc_get_product( $post->ID ); | |
$attributes_to_check = array( 'pa_your-attribute1', 'pa_your-attribute2', 'pa_your-attribute3' ); // Add your attribute slugs here | |
foreach ( $product->get_attributes() as $taxonomy => $wc_attribute ) { | |
if ( in_array( $taxonomy, $attributes_to_check ) ) { | |
$term_slugs = $wc_attribute->get_slugs(); | |
// Prefix the slug(s) with the taxonomy | |
$term_slugs = array_map( function( $slug ) use ( $taxonomy ) { | |
return $taxonomy . '-' . $slug; | |
}, $term_slugs ); | |
$custom_classes = array_merge( $custom_classes, $term_slugs ); | |
} | |
} | |
} | |
return array_merge( $classes, $custom_classes ); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Define a list of product attributes here:
$attributes_to_check = array( 'pa_your-attribute1', 'pa_your-attribute2', 'pa_your-attribute3' );
To return the plugin slugs as post_class on single product and in loop.