我将我的答案分为 3 个部分。目的是添加现有添加到购物车按钮的副本,但有 1 个差异,我们将使用该差异进行重定向。
第 1 步) 添加(复制)添加到购物车按钮可以通过调整/覆盖模板文件来完成,但也可以通过使用模板文件中的可用挂钩来完成,例如woocommerce_after_add_to_cart_button 钩子
// Add new/extra button
function action_woocommerce_after_add_to_cart_button() {
global $product;
// Button text
$button_text = __( 'My new text', 'woocommerce' );
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Simple products
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>';
// Variable products
} 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', 'action_woocommerce_after_add_to_cart_button', 10 );
这会为简单且可变的产品添加一个现有添加到购物车按钮的副本,但有 1 个区别。即:单击按钮时,通过jQuery添加一个隐藏的输入字段(步骤2)。
步骤 2) 这是添加具有特定值的隐藏输入字段的代码。我通过动作钩子添加了 jQuery,但这也可以包含在外部 js 文件中。
// Add jQuery to footer
function action_wp_footer() {
// Only on single product page
if ( is_product() ) {
?>
<script type="text/javascript">
jQuery( function($) {
// Add to cart button or custom button is clicked
$( document ).on( 'click', '.custom_redirect_button', function () {
// NOT disabled
if ( ! $( this ).hasClass( 'disabled' ) ) {
// Add hidden input field after
$( this ).after( '<input type="hidden" name="custom-redirect" value="my-value" />' );
}
});
});
</script>
<?php
}
}
add_action( 'wp_footer', 'action_wp_footer', 10 );
第 3 步) 从隐藏的输入字段中获取值,当它匹配时,它就是我们的自定义按钮,我们应用自己的 url。
// Redirect
function filter_woocommerce_add_to_cart_redirect( $redirect_url, $product ) {
// If value isset
if ( isset( $_REQUEST['custom-redirect'] ) ) {
// If equal to
if ( $_REQUEST['custom-redirect'] == 'my-value' ) {
// URL to redirect to (1 is the page ID here)
$redirect_url = get_permalink( 1 );
}
}
return $redirect_url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'filter_woocommerce_add_to_cart_redirect', 10, 2 );