[英]Remove custom quantity field when product out of stock on WooCommerce archives
[英]Replace quantity field with a form if product is out of stock in Woocommerce
在woocommerce中,使用聯系Form 7插件,當產品缺貨時,我試圖用表格替換產品摘要中的產品數量字段。
它在各種產品上都可以正常工作,但在簡單的產品上,它仍然顯示表格和數量框。
感覺就像我忽略了一些非常基本的內容。
我已經用“ simple”和“ variable”替換了不同的echo
,以找出顯示的是哪種形式, 但是在簡單的產品上,它仍然顯示'variable'形式 。
這是我的代碼:
add_action( 'woocommerce_single_product_summary', 'add_form' );
function add_form() {
global $product;
if( $product->is_type( 'simple' ) ){
// a simple product
if(!$product->is_in_stock( )) {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
//echo "simple";
}
} elseif( $product->is_type( 'variable' ) ){
// a variable product
$count_in_stock == 0;
$variation_ids = $product->get_children(); // Get product variation IDs
foreach( $variation_ids as $variation_id ){
$variation = wc_get_product($variation_id);
if( $variation->is_in_stock() )
$count_in_stock++;
}
}
if( $count_in_stock == 0 ) {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
//echo "variable";
}
}
嘗試以下代碼,當產品“缺貨”時(對於所有產品類型,包括可變產品) ,它將替換數量字段並使用表格添加到購物車按鈕 。
您說“在簡單產品上,它仍然顯示'可變'形式” :這是因為在簡單產品和可變產品上都使用相同的簡碼。 因此,您將需要為簡單產品添加正確的不同簡碼。
編碼:
add_action( 'woocommerce_single_product_summary', 'action_single_product_summary_callback', 4 );
function action_single_product_summary_callback() {
global $product;
// Variable products
if ( $product->is_type( 'variable' ) ){
$count_in_stock = 0;
foreach ( $product->get_visible_children() as $variation_id ) {
$variation = wc_get_product($variation_id);
if( $variation->is_in_stock() ) {
$count_in_stock++;
}
}
if ( $count_in_stock === 0 ) {
// Remove quantity field and add to cart button
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
// Display the contact form
add_action( 'woocommerce_single_variation', 'display_variable_product_out_of_stock_form', 20 );
}
}
// Other products (Simple … )
else {
if ( ! $product->is_in_stock() ) {
// Remove quantity field and add to cart button
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
// Display the contact form
add_action( 'woocommerce_single_product_summary', 'display_simple_product_out_of_stock_form', 30 );
}
}
}
// Form for variable products
function display_variable_product_out_of_stock_form() {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]');
}
// Form for Simple products
function display_simple_product_out_of_stock_form() {
echo do_shortcode('[contact-form-7 id="304" title="Contact stock"]'); // <== NOT the correct shortcode
}
代碼進入您的活動子主題(或活動主題)的function.php文件中。 經過測試和工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.