Reputation: 11
I have added code to display a "View Product Sample" button on the woocommerce page. The button functions correctly; however I would like for the button to display only for a certain category. The category that we have is "e-courses"
Here is the code I have used for the button:
add_action('woocommerce_after_add_to_cart_button','custom_button_by_categories');
function custom_button_by_categories() {
global $post;
$demoslug = $post->post_name;
$demourl = get_bloginfo('url').'/courses/'.$demoslug.'/';
$demotitle = esc_attr($post->post_title);
echo '<a href="'.$demourl.'" target="_blank" button type="submit" class="button sample">View Product Sample</a>';
}
Thank you for any help you can provide.
Upvotes: 0
Views: 1384
Reputation: 253867
You can do it using has_term()
Wordpress function (where you will have to define your product category).
You can use woocommerce_simple_add_to_cart
with a priority above 30 this way:
add_action( 'woocommerce_simple_add_to_cart', function(){
global $product, $post;
// Set HERE your product category (ID, name or slug)
if ( has_term( 'e-courses', 'product_cat', $post->ID ) ){
$demourl = get_bloginfo('url').'/courses/'.esc_attr($post->post_name).'/';
$demotitle = esc_attr($post->post_title);
echo '<a href="'.$demourl.'" target="_blank" button type="submit" class="button sample">View Product Sample</a>';
}
}, 31 );
Or also using your hook:
add_action('woocommerce_after_add_to_cart_button','custom_button_by_categories');
function custom_button_by_categories() {
// Set HERE your product category (ID, name or slug)
if ( has_term( 'e-courses', 'product_cat', $post->ID ) ){
global $post;
$demoslug = $post->post_name;
$demourl = get_bloginfo('url').'/courses/'.$demoslug.'/';
$demotitle = esc_attr($post->post_title);
echo '<a href="'.$demourl.'" target="_blank" class="button sample">View Product Sample</a>';
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works.
Upvotes: 1