I have successfully added a content after short description on single product page with
if (!function_exists('my_content')) {
function my_content( $content ) {
$content .= '<div class="custom_content">Custom content!</div>';
return $content;
}
}
add_filter('woocommerce_short_description', 'my_content', 10, 2);
I saw that in short-description.php
there was apply_filters( 'woocommerce_short_description', $post->post_excerpt )
so I hooked to that.
In the same way, I’d like to add a content after the add to cart button, so I found do_action( 'woocommerce_before_add_to_cart_button' )
, and now I am hooking to woocommerce_before_add_to_cart_button
. I’m using
if (!function_exists('my_content_second')) {
function my_content_second( $content ) {
$content .= '<div class="second_content">Other content here!</div>';
return $content;
}
}
add_action('woocommerce_after_add_to_cart_button', 'my_content_second');
But nothing happens. Can I only hook to hooks inside apply_filters
? From what I’ve understood so far by working with hooks is that you only need a hook name to hook to and that’s it. The first one was a filter hook, so I used add_filter
, and the second one is action hook so I should use add_action
, and all should work. So why doesn’t it?
Here, you need to echo content as it is add_action hook.
You need to do echo instead of return.
If you want the same thing on the shop archive page then you need to use the
woocommerce_loop_add_to_cart_link
filter to modify the add to cart button.When using ‘Action Hook’ adding the content(html) out of php would be easy.
If need to add dynamic content just echo that content using variables or add using some condition.
Filter hooks are useful to modify the existing content and needs a return statement (the modified)
Action hooks are mostly useful to add content.