Ibr*_*ors 1 php wordpress redirect filter woocommerce
我正在开发一个使用 woocommerce 和 wordpress 的项目,我需要在其中实现一个特定的功能。该项目要求某些产品标记为“租赁”。如果用户添加类别为“租赁”的产品,用户将被重定向到一个需要填写联系表单的页面,该表单将自动包含该产品的 sku。该产品不得添加到购物车。
我尝试使用过滤器“woocommerce_add_to_cart_redirect”。我检查了该产品是否属于某个类别,如果属于,它将被重定向到联系页面。问题是该产品已添加到购物车。
add_filter( 'woocommerce_add_to_cart_redirect', 'rv_redirect_on_add_to_cart' );
function rv_redirect_on_add_to_cart() {
//Get product ID
if ( isset( $_POST['add-to-cart'] ) ) {
$product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] );
//Check if product ID is in the proper taxonomy and return the URL to the redirect product
if ( has_term( 'rental', 'product_cat', $product_id ) ){
$product = wc_get_product( $product_id );
$_POST['rental-product-sku'] = $product->get_sku();
return get_permalink( get_page_by_path( 'rent-a-book' ) );
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用自定义验证“woocommerce_add_to_cart_validation”来检查产品是否属于该类别,如果属于,则返回 false。
add_action( 'woocommerce_add_to_cart_validation', 'add_the_date_validation', 11, 2 );
function add_the_date_validation($passed, $product_id ) {
$terms = wp_get_post_terms( $product_id, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;
if(count($categories) == 0){
return true;
}
if ( in_array( 'rental', $categories ) ) {
return false;
} else {
return true;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
问题是,如果验证返回 false,则不会加载重定向过滤器,并且用户不会重定向到联系页面。我已经研究了一段时间了,但我的尝试并没有成功。有人可以帮我弄这个吗?
谢谢
为什么不做这样的事情呢?
add_action( 'woocommerce_add_to_cart_validation', 'add_the_date_validation', 11, 2 );
function add_the_date_validation( $passed, $product_id ) {
if ( has_term( 'rental', 'product_cat', $product_id ) ){
// $product = wc_get_product( $product_id );
// $_POST['rental-product-sku'] = $product->get_sku();
wp_safe_redirect(get_permalink( get_page_by_path( 'rent-a-book' ) ) );
exit();
}
return $passed;
}
Run Code Online (Sandbox Code Playgroud)