0

I am trying to change the add_to_cart button text for all products based on category. For category 'course' with ID 330, I would like the button to read 'Register'.

For all other products, I would like it to read 'Buy Now'.

Here is what I have thus far in my functions.php:

add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_cat_add_to_cart_text' );
function custom_cat_add_to_cart_text( $default ) {
    global $post;
    $terms = get_the_terms( $post->ID, 'product_cat' );
    if ( array_key_exists( 330, $terms ) ) {
            return __( 'Register', 'course' );
    } else {
        return $default;
    }
}

This is failing to change the button text.

  • Try add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_cat_add_to_cart_text',10,2 ); – bravokeyl Oct 31 '15 at 6:06
  • Nothing changed. – Travis Patron Oct 31 '15 at 6:17
1

It's not working because:

get_the_terms( $post->ID, 'product_cat' )

yields an array of objects, to test against those objects you have to run a loop and pull a $term_id property out of each object.

Wordpress to the rescue! Wordpress has a helper method for that...

has_term(330,'product_cat', $post);

Use the has_term method to satisfy your conditional.

  • Worked like a charm. For others, this is what I have: add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_cat_add_to_cart_text' ); function custom_cat_add_to_cart_text( $default ) { global $post; $terms = get_the_terms( $post->ID, 'product_cat' ); if ( has_term(330, 'product_cat' , $post) ) { return __( 'Register', 'course' ); } elseif ( has_term(390, 'product_cat' , $post) ) { return __( 'Register', 'event' ); } else { return __( 'Buy Now' ); } } – Travis Patron Nov 6 '15 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.