[英]Adding quantity fields and add to cart buton on WooCommerce Shop page
我正在嘗試使用 WooCommerce 集成開發 WordPress 主題,但是,我對如何執行此特定的自定義 function 感到困惑:
單擊商店/存檔頁面上的任一分組產品,但不要重定向到該分組產品的頁面(我相信這是默認的 WooCommerce 行為),啟用下面的 div 與每個子單產品和數量字段。 應該可以通過 JavaScript 或 JQuery 實現。
再次通過 AJAX 或 JQuery 腳本,一旦達到分組產品的最大數量,這應該“禁用”或阻止用戶添加更多。
使用底部的添加到購物車按鈕將選擇添加到購物車。
現在,我很熟悉我的問題可以使用 JavaScript 和一些 CSS 技巧來解決,但我並不特別知道我應該使用哪個 WooCommerce 功能/鈎子來實現這個功能。
我已經嘗試過這段代碼,但它並沒有完全產生我想要做的效果:
/**
* Override loop template and show quantities next to add to cart buttons
*/
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
經過一番搜索和試驗,我找到了一個解決方案(或者更確切地說是一個 hack)。
事實證明,我只需將相關的添加到購物車 URL 即可將產品添加到購物車。 通過一點點 JavaScript 和 CSS 技巧,我理論上可以創建像圖像中的自定義功能。 我不太確定這是一種正確或最有效的方法,但絕對被認為是一種解決方法。
這是關於自定義添加到購物車 URL 的指南: https://www.businessbloomer.com/woocommerce-custom-add-cart-urls-ultimate-guide/
在這里發布它以防萬一有類似問題的人遇到這個問題。
提示:使用 JavaScript 構建自定義添加到購物車 URL。 例如,一個 function 會更改商店頁面上自定義添加到購物車按鈕的href
屬性。 有很多方法可以做到這一點。 但這是我的想法。
function whenProductClicked(){
let e = document.getElementById("YourAddToCart_Button_ID");
e.setAttribute("href", "https://yourdomain.com/?add-to-cart=3111");
}
The most important part is this bit of the URL: ?add-to-cart=3111
, when you have WooCommerce installed, this URL will trigger the add to cart functionality of WooCommerce. ?add-to-cart
是 function 和3111
是數據庫中現有產品的 ID。 因此,如果您需要偏離 WooCommerce 功能的標准方式,您將不得不嘗試並創造性地構建您的 URL。 就個人而言,我不會這樣做,但是,嘿。
當然,它可能會變得更復雜,並且需要進行大量檢查(至少根據我的要求),但這是我所想的最基本的形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.