Skip to content

Instantly share code, notes, and snippets.

@diggeddy
Last active February 6, 2024 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diggeddy/ad3c146e64b8dad417331703f21aa4c9 to your computer and use it in GitHub Desktop.
Save diggeddy/ad3c146e64b8dad417331703f21aa4c9 to your computer and use it in GitHub Desktop.
Woocommerce add a Specific Product Attribute as a class to `post_class`
<?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 );
});
@diggeddy
Copy link
Author

diggeddy commented Feb 6, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment