根据常规价格禁用Woocommerce产品

时间:2017-11-04 20:36:23

标签: php wordpress woocommerce visibility product

在我的Woocommerce网站上,我有一个插件,有时会将产品价格改为常规价格= null(出于不同的原因)。

如果发生这种情况,我们要禁用该产品,以便它不会在我们的在线商店中展示。我们怎么能在functions.php中做到这一点?

1 个答案:

答案 0 :(得分:0)

当常规价格为 NULL 时,此代码会停止目录和搜索中的产品,并且当正常价格不再为NULL时,将重新启用已停用的产品:< / p>

add_action( 'init', 'action_on_product_reg_price' );
function action_on_product_reg_price(){
    global $wpdb;

    // First query: Get the product Ids that have a NULL regular price
    $product_ids = $wpdb->get_col( "
        SELECT DISTINCT pm.post_id as product_id
        FROM  {$wpdb->prefix}postmeta as pm
        LEFT JOIN {$wpdb->prefix}postmeta AS pm2 ON pm2.post_id = pm.post_id
        WHERE (pm.meta_key = '_regular_price'
        AND (pm.meta_value IS NULL
        OR pm.meta_value LIKE 'null'))
        OR (pm2.meta_key LIKE '_force_visibility'
        AND pm2.meta_value IS NOT NULL)
    " );

    // Disable the products from catalog and search
    if(count($product_ids) > 0){
        foreach($product_ids as $product_id){
            $product = wc_get_product($product_id);
            if($product->get_catalog_visibility() != 'hidden' ) {
                $product->set_catalog_visibility('hidden'); // visible
                $product->save();
                update_post_meta( $product_id, '_force_visibility', 1 );
            }
        }
    }

    // 2nd query: Get the product Ids that have changed from NULL regular price
    $product_ids = $wpdb->get_col( "
        SELECT DISTINCT pm.post_id as product_id
        FROM  {$wpdb->prefix}postmeta as pm
        INNER JOIN {$wpdb->prefix}postmeta AS pm2 ON pm2.post_id = pm.post_id
        WHERE pm.meta_key = '_regular_price'
        AND (pm.meta_value IS NOT NULL
        OR pm.meta_value NOT LIKE 'null')
        AND pm2.meta_key LIKE '_force_visibility'
        AND pm2.meta_value = '1'
    " );

    // Re-enable catolog and search visibility
    if(count($product_ids) > 0){
        foreach($product_ids as $product_id){
            $product = wc_get_product($product_id);
            if($product->get_catalog_visibility() != 'visible' ) {
                $product->set_catalog_visibility('visible'); // visible
                $product->save();
                update_post_meta( $product_id, '_force_visibility', NULL );
            }
        }
    }
}

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中。

测试并使用WooCommerce 3 +