1

So I'm using the conditional of tho code Snippet from this example, with this thread code with success:

BUT It's no longer working after updating my WordPress Core and WooCommerce Plugin.

if ( is_product() && has_term( 'sample-category', 'product_cat' ) ){

    add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
    function add_custom_button() {
        global $products;

        $product_link = get_permalink( $products->id );
        $sample_link = substr($product_link, 0, -1) . '-swatch-card/';
        echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Order a Sample", "my_theme_slug" )  . '</a>';

    }

}

Child Plugin still has the proper code in the function.php file.

How can I solve this issue please?

Thanks

Community
  • 1
  • 1
Carlos Daniel
  • 127
  • 2
  • 11

1 Answers1

3

Try this way may be, using $post global object and embedding the conditional inside your function:

add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_button', 10, 0 );
function add_custom_button() {
    global $post;
    if ( has_term( 'collection', 'product_cat', $post->ID ) ) {
        $product_link = get_permalink( $post->ID );
        $sample_link = substr($product_link, 0, -1) . '-swatch-card/';
        echo '<a class="button alt btn-sample" href="' . esc_url( $sample_link ) .'">' . __( "Order a Sample", "my_theme_slug" )  . '</a>';
    }
};

The conditional has_term() needs sometimes it's third argument to work… In function.php it can't find the current post So in this case is better to embed it inside the function after $post or $product global object.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399