phpwoocommerceattributescustom-taxonomywpml

WooCommerce display Product Attributes on shop page compatible with multi-language


I have managed to change WooCommerce to Show attributes on the shop page. however, my site is multi-language, how can I make this function multi-language?

add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
function display_size_attribute() {
    global $product;

    if ( $product->is_type('simple') ) {
        $taxonomy = 'klasse-graafmachine-ton';
        echo '<span class="attribute-s">Klasse graafmachine (t): ' . $product->get_attribute($taxonomy) . '</span>','<br>';
    }
}

Solution

  • You should not use custom product attributes (created locally on the product), you should use instead global product attributes taxonomies set globally on Product Attributes section.

    enter image description here

    Then configure terms for your product attribute...

    Now on each product you will configure the Attribute (and select the term for it):

    enter image description here

    Now you can translate this product attribute and its terms in your multilingual plugin as it's a taxonomy like product category or product tag.

    Then you can use the following revised code to display the attribute in archives:

    add_action( 'woocommerce_after_shop_loop_item_title', 'display_size_attribute', 5 );
    function display_size_attribute() {
        global $product;
    
        $taxonomy = 'pa_klasse-graafmachine-ton';
    
        if ( $product->is_type('simple') && ( $term_name = $product->get_attribute($taxonomy) ) ) {
            printf( '<span class="attribute-s">%s: %s</span><br>', wc_attribute_label($taxonomy, $product), $term_name );
        }
    }
    

    It should work.

    Note: The taxonomy to be used in the code will be (starts always with "pa_").