在woocommerce中,使用contact Form 7插件,当产品缺货时,我试图用产品摘要中的产品数量字段替换产品数量字段。
它适用于可变产品,但在简单的产品上,它仍然显示形式和数量框。
感觉就像我忽略了一些非常基本的东西。
我用“简单”和“变量”替换了不同的echo
以找出显示的形式,但在简单的产品上它仍然显示“变量”形式。
这是我的代码:
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文件中。经过测试和工作。