sinanisler logo

Variable Product Attribute List, Shortcode, WooCommerce

With this shortcode, you can get any variable product attributes list. If the count is true it shows how many in the list as a number only.

[snn_get_attributes name=”Color”]

[snn_get_attributes name=”Color” count=”true”]


// [snn_get_attributes name="Color"]
//
// [snn_get_attributes name="Color" count="true"]
// 
function snn_get_attributes_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'name' => '', 
        'count' => 'false' 
    ), $atts, 'snn_get_attributes' );
    
    global $product;
    
    if ( ! is_a( $product, 'WC_Product' ) ) {
        return 'No product found.';
    }

    $attributes = $product->get_attributes();
    
    // Sanitize the attribute name
    $attribute_name = sanitize_title( $atts['name'] );
    
    // Check if it's a custom product attribute
    if ( isset( $attributes[ $attribute_name ] ) ) {
        // Custom product attribute
        $attribute = $attributes[ $attribute_name ];
        
        // Check if the attribute is not empty
        if ( ! empty( $attribute->get_options() ) ) {
            // If count is enabled, return the count of options
            if ( $atts['count'] === 'true' ) {
                return count( $attribute->get_options() );
            }
            
            // Otherwise, return the attribute options
            return implode( ', ', $attribute->get_options() );
        }
    }

    return '';
}

// Register the shortcode [snn_get_attributes name="Width" count="true"]
add_shortcode( 'snn_get_attributes', 'snn_get_attributes_shortcode' );





Leave the first comment