我已成功在单个产品页面上添加简短描述后的内容
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');
如果需要添加动态内容,只需使用变量回显该内容或使用某些条件添加。
过滤器钩子对于修改现有内容很有用,需要一个return语句(修改后的)
动作挂钩对于添加内容最有用。
上面的代码是在所有产品页面上添加相同的链接。将其插入到functions.php文件中以仅编辑单个产品页面:
add_action( 'woocommerce_after_add_to_cart_button', 'additional_single_product_button_2', 20 );
function additional_single_product_button_2() {
global $product;
// Define your targeted product IDs in the array below
$targeted_product_ids = array( put product ID here );
if( in_array( $product->get_id(), $targeted_product_ids ) ) {
$link = 'put your link here';
$name = esc_html ( "button with external link", "woocommerce" ); // <== Here set button name
$class = 'button alt';
$style = 'margin-left: 1em';
// Output
echo '<button type="button" style="' . $style . '" class="' . $class . '" onclick="window.open(\'' . $link . '\', \'_blank\')">' . $name . '</button>';
}
}
如果您想为带有其他链接的其他产品页面制定规则,则需要更改功能名称。