sam*_*lla 1 php wordpress product cart woocommerce
我正在尝试将所有产品重定向到一个自定义页面,除了 3 个进入结帐的产品(这部分有效)。
function my_custom_add_to_cart_redirect( $url ) {
if ( ! isset( $_REQUEST['add-to-cart'] ) || ! is_numeric( $_REQUEST['add-to-cart'] ) ) {
$url = get_permalink( 16 ); // URL page ID to redirect for all pages but below mentioned
return $url;
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );
// Only redirect the product IDs in the array to the checkout
if ( in_array( $product_id, array( 999, 997, 872) ) ) {
$url = WC()->cart->get_checkout_url();
}
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
Run Code Online (Sandbox Code Playgroud)
要使您的代码按预期工作,非常简单。下面我对你的代码做了一些更改:
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect', 10, 1 );
function my_custom_add_to_cart_redirect( $url ) {
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );
// Only redirect the product IDs in the array to the checkout
if ( in_array( $product_id, array( 999, 997, 872) ) ) {
// This is more correct to get the checkout URL
$url = get_permalink( get_option('woocommerce_checkout_page_id') );
} else {
// All other products that are not in your array will be redirected to this URL
$url = get_permalink( 16 ); // URL page ID to redirect for all pages but below mentioned
}
return $url;
}
Run Code Online (Sandbox Code Playgroud)
此代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
这段代码已经过测试并且可以工作。