如果满足条件,则停止 WooCommerce 简单产品发布

问题描述 投票:0回答:1

我想检查我的店长是否可以发布产品,例如商店不能有超过30个简单产品。

我遇到了这个代码:

add_action( 'woocommerce_new_product', 'on_product_save', 10, 1 );
add_action( 'woocommerce_update_product', 'on_product_save', 10, 1 );
function on_product_save( $product_id ) {
     $product = wc_get_product( $product_id );
     // do something with this product
}

但我不知道如何向用户显示管理消息并退出“错误”保存,...

有什么想法吗?

php jquery woocommerce product message
1个回答
0
投票

尝试以不同的方式思考......

如果已达到 30 个“简单”产品的限制,您可以做的是隐藏管理新产品上的“发布”Metabox 内容。

为此,您需要首先检查条件函数中发布了多少个简单产品:

// Conditional function: Check if new simple product is allowed (the limit set to 30)
function is_new_simple_product_allowed( $limit = 30 ) {
    // Get all published simple product IDs
    $product_ids = get_posts(['post_type' => 'product', 'post_status' => 'publish', 'numberposts' => -1, 'fields' => 'ids']);
    return count($product_ids) < $limit;
}

然后我们在以下两个函数中使用该条件函数:

1)。在管理新产品页面上显示错误通知:

add_action( 'admin_notices', 'sample_admin_notice__success' );
function sample_admin_notice__success() {
    global $pagenow, $typenow;

    if ( $pagenow === 'post-new.php' && $typenow === 'product' && ! is_new_simple_product_allowed() ) {
        printf( '<div class="%1$s"><p>%2$s</p></div>', 'error', 
        esc_html__( 'You are not allowed to add a new simple product as the allowed limit for simple products has already been reached.', 'woocommerce' ) );
    }
}

Seenshot - 当不允许新的简单产品时显示错误通知

Displayed error notice

2)。仅当使用 JavaScript 选择的产品类型为“简单”时,才在管理新产品上显示或隐藏“发布”Metabox 内容:

add_filter( 'admin_footer', 'new_product_show_or_hide_publish_metabox_js');
function new_product_show_or_hide_publish_metabox_js() {
    global $pagenow, $typenow;

    if ( $pagenow === 'post-new.php' && $typenow === 'product' && ! is_new_simple_product_allowed() ) :
    ?><script>
    jQuery( function($) {
        function show_hide_publish_metabox_content( productType ){
            if ( productType === 'simple' ) {
                $('#submitpost').hide();
                $( '<div id="replace-buttons" style="padding:0 10px; color:#d63638;"><p>New simple product is not allowed.</p></div>' ).insertAfter('#submitpost');
            } else {
                $('#submitpost').show();
                $('#replace-buttons').remove();
            }
        }
        var productType = $('#product-type').val();
        show_hide_publish_metabox_content( productType );
        
        $('#product-type').on('change', function(){
            productType = $(this).val();
            show_hide_publish_metabox_content( productType );
            
        });
    });
    </script><? 
    endif;
}

Seenshot - 当不允许新建简单产品时(且所选产品类型为简单),您将得到:

Seenshot - 如果您更改产品类型,例如更改为“可变产品”,您将恢复默认的 Metabox 内容:

Normal Metabox

您还可以使用重定向到产品列表,例如在此线程中

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.