Carlos Daniel Carlos Daniel - 3 months ago 20
PHP Question

WooCommerce - Display Code Only in Certain Category

So I'm using this Snippet from this example.

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


It's no longer working after updating my WordPress Core and WooCommerce Plugin.
Child Plugin still has the proper code in the function.phps file.

Answer

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>';
    }
};