我已经成功地用在单个产品页面上添加了简短描述后的内容
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);
我看到在short-description.php
中有apply_filters( 'woocommerce_short_description', $post->post_excerpt )
所以我迷上了它。
同样,我想在添加到购物车按钮后添加一个内容,所以我找到了do_action( 'woocommerce_before_add_to_cart_button' )
,现在我正在连接到woocommerce_before_add_to_cart_button
。我正在使用
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');
但什么也没发生。我只能挂到apply_filters
内部的挂钩吗?到目前为止,我对钩子的理解是,你只需要一个钩子名称就可以挂接到它。第一个是过滤器钩子,所以我使用了add_filter
,第二个是动作钩子,所以我们应该使用add_action
,一切都可以。为什么不呢?
这里,您需要回显内容,因为它是add_action钩子。
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );
/*
* Content below "Add to cart" Button.
*/
function add_content_after_addtocart_button_func() {
// Echo content.
echo '<div class="second_content">Other content here!</div>';
}
您需要执行echo而不是return。
add_action( 'woocommerce_after_add_to_cart_button', 'ybc_after_add_to_cart_btn' );
function ybc_after_add_to_cart_btn(){
//add text OR HTML here
echo '<p>After custom text here</p>';
}
如果你想在商店档案页面上看到同样的东西,那么你需要使用woocommerce_loop_add_to_cart_link
过滤器来修改添加到购物车按钮。
当使用"Action Hook"时,从php中添加内容(html)会很容易。
if (!function_exists('my_content_second')) {
function my_content_second( $content ) {
?>
<div class="second_content">Other content here!</div>;
<?php
}
}
add_action('woocommerce_after_add_to_cart_button', 'my_content_second');
如果需要添加动态内容,只需使用变量回显该内容或使用某些条件添加即可。
过滤器挂钩对于修改现有内容很有用,并且需要一个返回语句(修改后的)
操作挂钩对于添加内容非常有用。