
在构建复杂的 WooCommerce 网店时,有时我们需要在单产品页面提供额外的购买或询价选项,例如一个“添加到报价”按钮,它应具备与“添加到购物车”按钮类似的功能,但在点击后重定向到不同的页面。本教程将指导您如何实现这一需求,确保所有自定义购物车项数据等相关钩子依然正常工作。
首先,我们需要在现有“添加到购物车”按钮下方添加一个新的按钮。这可以通过 WooCommerce 提供的动作钩子 woocommerce_after_add_to_cart_button 来实现,避免直接修改模板文件。新按钮将与原始按钮共享大部分功能,但会额外添加一个用于后续识别的 CSS 类。
// 在添加到购物车按钮后添加新的自定义按钮
function custom_add_to_quote_button() {
global $product;
// 自定义按钮文本
$button_text = __( '添加到报价', 'woocommerce' ); // 可根据需求修改文本
// 确保当前是有效的 WooCommerce 产品
if ( is_a( $product, 'WC_Product' ) ) {
// 针对简单产品
if ( $product->is_type( 'simple' ) ) {
echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ) . '" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
// 针对可变产品
} elseif( $product->is_type( 'variable' ) ) {
echo '<button type="submit" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
}
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'custom_add_to_quote_button', 10 );代码说明:
为了区分原始加购按钮和我们新添加的自定义按钮,我们需要在自定义按钮被点击时,通过 JavaScript 动态地向表单中添加一个隐藏字段。这个隐藏字段将作为后端重定向逻辑的判断依据。
将以下 jQuery 代码添加到您的主题的 functions.php 文件中,或者通过外部 JS 文件引入(推荐)。
// 在页面底部添加 jQuery 脚本
function custom_redirect_script_to_footer() {
// 仅在单产品页面加载脚本
if ( is_product() ) {
?>
<script type="text/javascript">
jQuery( function($) {
// 监听自定义重定向按钮的点击事件
$( document ).on( 'click', '.custom_redirect_button', function () {
// 确保按钮未被禁用
if ( ! $( this ).hasClass( 'disabled' ) ) {
// 在按钮后添加一个隐藏的输入字段
$( this ).after( '<input type="hidden" name="custom-redirect" value="my-quote-value" />' );
}
});
});
</script>
<?php
}
}
add_action( 'wp_footer', 'custom_redirect_script_to_footer', 10 );代码说明:
最后一步是利用 WooCommerce 的 woocommerce_add_to_cart_redirect 过滤器来拦截默认的重定向行为,并根据我们添加的隐藏字段来决定是重定向到购物车页面还是自定义页面。
// 过滤添加到购物车后的重定向 URL
function custom_add_to_cart_redirect_logic( $redirect_url, $product ) {
// 检查是否存在自定义重定向标记
if ( isset( $_REQUEST['custom-redirect'] ) ) {
// 如果标记的值与我们预设的值匹配
if ( $_REQUEST['custom-redirect'] == 'my-quote-value' ) {
// 设置自定义重定向 URL (例如:页面ID为1的页面)
$redirect_url = get_permalink( 1 ); // 请将 '1' 替换为您希望重定向到的页面ID或直接提供URL
}
}
return $redirect_url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect_logic', 10, 2 );代码说明:
.single_product .custom_redirect_button {
background-color: #0073aa; /* 示例颜色 */
color: #fff;
/* 其他样式调整 */
}通过以上步骤,您已经成功在 WooCommerce 单产品页面复制了一个“添加到购物车”按钮,并为其配置了独立的自定义重定向功能,同时保持了原始加购按钮的默认行为。
以上就是WooCommerce 单产品页复制加购按钮并实现自定义重定向教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号