![](/img/trans.png)
[英]Add multiple custom data arrays to cart item on WooCommerce custom Ajax add to cart
[英]Disable ajax add to cart on first item and custom redirect it on Woocommerce
嗨,我正在WOOCOMMERCE網站上工作,當用戶嘗試將其第一個產品添加到購物車時,我試圖將用戶重定向到自定義頁面。
重定向僅應針對購物車中的第一個產品進行。
當用戶在購物車中添加兩個或更多產品時,正常的添加到購物車的ajax應該會起作用。
首先,我嘗試使用以下功能重定向到第一個產品的自定義頁面
function my_custom_add_to_cart_redirect( $url ) {
if (WC()->cart->get_cart_contents_count() == 0)
$url = get_permalink( 1172 ); /* ID of the page is entered */
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
上面的代碼確實重定向到了自定義頁面,但所有添加到購物車的產品都會發生此情況。
此外,當在WOOCommerce設置中未選中“添加成功后重定向到購物車頁面”字段時,該功能不起作用。
誰能用正確的方法幫助我?
您需要一些其他代碼來在購物車為空時禁用添加到購物車並更改您的代碼:
// Replacing the ajax add to cart button by a link to the product when cart is empty
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product ) {
if( WC()->cart->is_empty() && $product->is_type('simple') ){
$button_text = __( "View product", "woocommerce" );
$button = '<a class="button product_type_simple" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
}
return $button;
}
// Custom Redirect on first added to cart only
add_filter( 'woocommerce_add_to_cart_redirect', 'custom_add_to_cart_redirect_on_first_item' );
function custom_add_to_cart_redirect_on_first_item( $url ) {
// Redirect on first added item
if ( WC()->cart->get_cart_contents_count() == 1 ) {
return get_permalink( 1172 ); // ID of the page
}
}
代碼進入您的活動子主題(或活動主題)的function.php文件中。 經過測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.