Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active July 12, 2021 11:16
Show Gist options
  • Save jorpdesigns/c5158c8bef856ed43827fa61cd54fd1b to your computer and use it in GitHub Desktop.
Save jorpdesigns/c5158c8bef856ed43827fa61cd54fd1b to your computer and use it in GitHub Desktop.
Snippet to get attributes on WooCommerce product page
<?php
// You can add this function to any hook listed here - https://www.businessbloomer.com/woocommerce-visual-hook-guide-single-product-page/
function product_attributes() {
global $product;
// GET SPECIFIC ATTRIBUTE
$attribute = $product->get_attribute( 'pa_attribute' );
$specificAttribute = $product->get_attribute( 'pa_specific-attribute' );
// GET SPECIFIC ATRIBUTE SLUG
$attributeTerm = get_term_by( 'name', $attribute, 'pa_attribute' );
$attributeSlug = $attributeTerm->slug;
// GET ALL ATTRIBUTES
$attributes = $product->get_attributes();
foreach ( $attributes as $attribute ) {
// FOR NON-TAXONOMY ATTRIBUTES
if ( ! $attribute->is_taxonomy() ) {
$attributeLabel = $attribute->get_name();
$attributeValues = esc_html( implode( ', ', $attribute->get_options() ) );
}
// FOR TAXONOMY ATTRIBUTES
if ( $attribute->is_taxonomy() ) {
$attributeName = $attribute->get_name();
$terms = wp_get_post_terms( $product->get_id(), $attributeName, 'all' );
$tax = $terms[0]->taxonomy;
$object_taxonomy = get_taxonomy($tax);
if ( isset ($object_taxonomy->labels->singular_name) ) {
$attributeLabel = $object_taxonomy->labels->singular_name;
}
if ( isset( $object_taxonomy->label ) ) {
$attributeLabel = $object_taxonomy->label;
if ( 0 === strpos( $attributeLabel, 'Product ' ) ) {
$attributeLabel = substr( $attributeLabel, 8 );
}
}
$attributeTermsArray = array();
foreach ( $terms as $term ) {
$single_term = esc_html( $term->name );
array_push( $attributeTermsArray, $single_term );
}
$attributeValues = esc_html( implode(', ', $attributeTermsArray) );
}
// GET VALUES FOR FOR SPECIFIC ATTRIBUTE ONLY e.g. Size
if ( $attributeLabel == "Size" ) {
$attributeValues = esc_html( implode( ', ', $attribute->get_options() ) );
}
// CHECK IF ATTRIBUTE IS USED FOR CREATING VARIATIONS
if ( $attribute->get_variation() ) {
// Do something
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment