简体   繁体   中英

List all variations displaying their attributes linked to the variation on Woocommerce products loop

I would like to add a link to each attribute so when clicking the visitor has the variation selected.

Basically adding a link like https://exampl.com/product/t-shirt/?attribute_pa_size=l to each term.

Based on Display Variable Product Attributes and Terms on Woocommerce Archives answer code, I have tried to insert the term link using:

$term_link = get_term_link( $term );

But it doesn't give a link to selected product attribute.

Any help is appreciated.

When you have multiple attributes, The link to a variation is a combination of terms from each attribute… So you can't have a link on the term itself, that will go to a specific variation, as one term is related to multiple variations.

So you need something different. The best way is to list all visible variations for variable products displaying their attributes linked to the variation in product loops as follows:

add_action( 'woocommerce_after_shop_loop_item', 'product_variable_linked_variations_on_loop', 7 );
function product_variable_linked_variations_on_loop() {
    global $product;

    if( $product->is_type('variable') ) { // Only for variable products
        $output = array(); // Initializing

        // Loop through visible children Ids (variations ids)
        foreach( $product->get_visible_children() as $variation_id ) {
            $variation  = wc_get_product($variation_id); // The varition object instance
            $permalink  = $variation->get_permalink(); // The link to the variation
            $attributes = array(); // Initializing

            // Loop through attributes
            foreach( $variation->get_attributes() as $attribute => $value ) {
                $attribute_label = wc_attribute_label( $attribute, $product );
                $attribute_value = $variation->get_attribute($attribute);
                $attributes[]    = $attribute_label . ': ' . $attribute_value;
            }
            $output[] = '<a href="' . $permalink . '">' . implode(', ', $attributes) . '</a>';
        }

        echo '<div class="product-attributes">';
        echo '<span>' . implode('</span><br><span>', $output) . '</span>';
        echo '</div>';
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM