Show specific multiple attributes in WooCommerce product page

154 Views Asked by At

I am trying to show multiple attributes on WooCommerce product page. I found this code but it is for only one attribute. I am not a PHP developer so I can't make the code to get more attributes. Can anyone help me?

function get_product_attributes_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'id'    => get_the_ID(),
    ), $atts, 'display-attributes' ) );

    global $product;

    if ( ! is_a($product, 'WC_Product') ) {
        $product = wc_get_product( $id );
    }
    if ( is_a($product, 'WC_Product') ) {
        $styletypes = $product->get_attribute( 'styletypes' );
        return '<div class="product-attributes"><strong>Styletype</strong>: ' . $styletypes . '<div>';
    }
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );
1

There are 1 best solutions below

1
mujuonly On
function get_product_attributes_shortcode($atts) {
    
    extract(shortcode_atts(array('id' => get_the_ID(),), $atts, 'display-attributes'));

    global $product;

    if (!is_a($product, 'WC_Product')) {
        $product = wc_get_product($id);
    }
    if (is_a($product, 'WC_Product')) {
        $attr_str = '<div class="product-attributes">';
        foreach ($product->get_attributes() as $attr_key => $attr) {
            $attr_str.= '<strong>'.$attr['name'].'</strong>: ';
            foreach ($attr['options'] as $attr_opt) {
                $attr_str.= $attr_opt .' | ';
            }
            $attr_str = rtrim($attr_str, ' | ');
            $attr_str.= '<br/>';
        }
        $attr_str.= '</div>';
        return $attr_str;
    }
}

add_shortcode('display-attributes', 'get_product_attributes_shortcode');