Home > front end >  Wordpress - Return multiple product attributes
Wordpress - Return multiple product attributes

Time:02-15

I'm trying to replace the product title on the WooCommerce product catalog by some product information, based on product attributes.

I've been able to create a working snippet for one attribute, with this code:

if(!function_exists('replace_title_custom_attribute')):

    function replace_title_custom_attribute( $title, $id ){

        $taxonomy = 'pa_model-number';

        $terms = get_the_terms($id, $taxonomy);

        if( ! is_wp_error($terms) && ! empty($terms) && ($term = $terms[0]) ){
            return $term->name;
        }

        return $title;
    }

    add_action('woocommerce_before_shop_loop_item', function(){
        add_filter('the_title', 'replace_title_custom_attribute', 10, 2);
    }, 10);

    add_action('woocommerce_after_shop_loop_item', function(){
        remove_filter('the_title', 'replace_title_custom_attribute', 10);
    }, 10);

endif;

But now, I want to show extra information based on another pa_another_attribute. I think I'll need something like an array here, but can't seem to figure out how to do this.

Such that in the end the information looks like this in the front-end "pa_modelnumber" - "pa_another_attribute"

Hope you can help me in the right direction here, thanks!

CodePudding user response:

I revised your code. Try the below code.

if(!function_exists('replace_title_custom_attribute')):

    function replace_title_custom_attribute( $title, $id ){

        $taxonomy = 'pa_color'; // replace with your attribute name

        $terms = get_the_terms($id, $taxonomy);

        if( ! is_wp_error($terms) && ! empty($terms) && ($term = $terms[0]) ){
            $title1 = $term->name;
        }

        $taxonomy = 'pa_size'; // replace with your attribute name

        $terms = get_the_terms($id, $taxonomy);

        if( ! is_wp_error($terms) && ! empty($terms) && ($term = $terms[0]) ){
            $title2 = $term->name;
        }

        if( $title1 != '' && $title2 != '' ){
            $title = $title1.' - '.$title2;
        }elseif ( $title1 != '' ) {
            $title = $title1;
        }elseif ( $title2 != '' ) {
            $title = $title2;
        }else{
            $title = $title;
        }

        return $title;
        
    }

    add_action('woocommerce_before_shop_loop_item', function(){
        add_filter('the_title', 'replace_title_custom_attribute', 10, 2);
    }, 10);

    add_action('woocommerce_after_shop_loop_item', function(){
        remove_filter('the_title', 'replace_title_custom_attribute', 10);
    }, 10);

endif;

Tested and works.

enter image description here

  • Related