将缺货产品发送至垃圾箱

时间:2017-03-16 10:48:49

标签: php wordpress woocommerce product hook-woocommerce

WooCommerce中有一项功能可以隐藏商店中的缺货产品。但是,此功能仅在我使用本机WooCommerce短代码时才有效,如果正在使用其他插件在网站的其他部分显示产品,则此功能无效。

所以,我认为废弃该产品将是一个更好的方式摆脱Out Of Stock产品。 我不希望永久删除,以防我想让工作更轻松,并在将来恢复这些产品,但如果没有别的办法,我会欢迎它。

我只是在学习一点PHP。如果您有任何想法,请告诉我。

2 个答案:

答案 0 :(得分:0)

  

在WordPress中,所有的东西都被视为不同的帖子   post_type,所以每当帖子/产品更新save_post时都是如此   调用。

function wh_trashOutOfStockProduct($post_id, $post, $update) {

    $post_type = get_post_type($post_id);

    // If this isn't a 'product' post, don't update it.
    if ('product' != $post_type)
        return;
    $product = wc_get_product($post_id);
    //if product is Out of Stock trash it
    if (!$product->is_in_stock()) {
        wp_trash_post($post_id);
    }
}

add_action('save_post', 'wh_trashOutOfStockProduct', 10, 3);

代码进入您的活动子主题(或主题)的function.php文件。或者也可以在任何插件php文件中。

<小时/> <强>已更新
一次性使用功能

add_action('wp', 'wh_trashAllProductOnce');

function wh_trashAllProductOnce()
{
    $params = [
        'posts_per_page' => -1,
        'post_type' => 'product'
    ];
    $wc_query = new WP_Query($params);

    if ($wc_query->have_posts()) :
        while ($wc_query->have_posts()) :
            $wc_query->the_post();
            $product_id = get_the_ID();
            $product = wc_get_product($product_id);
            //if product is Out of Stock trash it
            if (!$product->is_in_stock())
            {
                wp_trash_post($product_id);
            }
        endwhile;
        wp_reset_postdata();
    else:
        _e('No Products');
    endif;
}

在活动主题functions.php文件中添加上述代码并运行您的网站只删除上述代码,它会删除所有缺货产品

<小时/> <强>已更新

如果您希望将代码保留更长时间,请减少查询和执行时间。

add_action('admin_init', 'wh_trashAllProductOnce');

function wh_trashAllProductOnce() {
    $current_user = wp_get_current_user();
    //if loggedin user does not have admin previlage
    if (!user_can($current_user, 'administrator')) {
        return;
    }
    $params = [
        'posts_per_page' => -1,
        'post_type' => 'product',
        'post_status' => 'publish'
    ];
    $wc_query = new WP_Query($params);
    if ($wc_query->have_posts()) :
        while ($wc_query->have_posts()) :
            $wc_query->the_post();
            $product_id = get_the_ID();
            $product = wc_get_product($product_id);
            //if product is Out of Stock trash it
            if (!$product->is_in_stock()) {
                wp_trash_post($product_id);
            }
        endwhile;
        wp_reset_postdata();
    endif;
}

在活动主题functions.php文件中添加上述代码,每当管理员登录仪表板并访问任何后端页面时,都会触发此功能。

  

请注意:建议使用上述任何一种方法   只有一次,或者只需要取消注释功能使用   它然后再评论它。

希望这有帮助!

答案 1 :(得分:0)

TabbedPage

您只需点击Woocommerce下的工具菜单即可完成此操作 - &gt;系统状态,请参见屏幕截图enter image description here

相关问题