从Woocommerce中的非销售产品中自动删除销售产品类别

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

在woocommerce中,我使用的是the code from this answer thread,它将“促销”产品类别分配给正在销售的产品(因此具有有效的销售价格)。

当产品没有成功销售时,我试图删除“促销”产品类别。当它们不再销售时,是否可以自动从“销售”类别中删除产品?

php wordpress woocommerce product custom-taxonomy
1个回答
1
投票

以下版本代码将自动从“销售”类别中删除产品,如果它们不再销售:

add_action( 'save_post_product', 'update_product_set_sale_cat' );
function update_product_set_sale_cat( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return $post_id;
    }
    if ( ! current_user_can( 'edit_product', $post_id ) ) {
        return $post_id;
    }
    if( get_post_status( $post_id ) == 'publish' && isset($_POST['_sale_price']) ) {
        $sale_price = $_POST['_sale_price'];

        if( $sale_price >= 0 && ! has_term( 'Sale', 'product_cat', $post_id ) ){
            wp_set_object_terms($post_id, 'sale', 'product_cat', true );
        } elseif ( $sale_price == '' && has_term( 'Sale', 'product_cat', $post_id ) ) {
            wp_remove_object_terms( $post_id, 'sale', 'product_cat' );
        }
    }
}

代码位于活动子主题(或活动主题)的function.php文件中。经过测试和工作。

相关:Adding "Sale" product category to products that are on sale in Woocommerce

© www.soinside.com 2019 - 2024. All rights reserved.