S
S
Sergey Shilov2018-06-16 20:44:21
WordPress
Sergey Shilov, 2018-06-16 20:44:21

How to display the name (label) of the woocommerce attribute?

Hey! Now I display only the value of the attribute, but I also need its name, has anyone done it?

global $product;
$terms = get_terms();

if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){

echo '<ul>';

foreach ( $terms as $term ) {

echo '<li>
        <span class="product-attr-list-label"><!-- тут нужен label --></span>
        <span class="product-attr-list-value">' . $term->name . '</span>
      </li>';
}
echo '
</ul>';

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Shilov, 2018-06-16
@Olivoin

Like this

global $product;
    $attributes = $product->get_attributes();
  
    if ( ! $attributes ) {
        return;
    }
  
    $out = '<ul class="custom-attributes">';
  
    foreach ( $attributes as $attribute ) {
  
  
        // skip variations
        if ( $attribute->get_variation() ) {
        continue;
        }
        $name = $attribute->get_name();
        if ( $attribute->is_taxonomy() ) {
  
            $terms = wp_get_post_terms( $product->get_id(), $name, 'all' );
            // get the taxonomy
            $tax = $terms[0]->taxonomy;
            // get the tax object
            $tax_object = get_taxonomy($tax);
            // get tax label
            if ( isset ( $tax_object->labels->singular_name ) ) {
                $tax_label = $tax_object->labels->singular_name;
            } elseif ( isset( $tax_object->label ) ) {
                $tax_label = $tax_object->label;
                // Trim label prefix since WC 3.0
                if ( 0 === strpos( $tax_label, 'Product ' ) ) {
                   $tax_label = substr( $tax_label, 8 );
                }                
            }
  
  
            $out .= '<li class="' . esc_attr( $name ) . '">';
            $out .= '<span class="attribute-label">' . esc_html( $tax_label ) . ': </span> ';
            $out .= '<span class="attribute-value">';
            $tax_terms = array();
            foreach ( $terms as $term ) {
                $single_term = esc_html( $term->name );
                // Insert extra code here if you want to show terms as links.
                array_push( $tax_terms, $single_term );
            }
            $out .= implode(', ', $tax_terms);
            $out .= '</span></li>';
 
        } else {
            $value_string = implode( ', ', $attribute->get_options() );
            $out .= '<li class="' . sanitize_title($name) . ' ' . sanitize_title( $value_string ) . '">';
            $out .= '<span class="attribute-label">' . $name . ': </span> ';
            $out .= '<span class="attribute-value">' . esc_html( $value_string ) . '</span></li>';
        }
    }
  
    $out .= '</ul>';
  
    echo $out;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question