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

1 php wordpress product custom-taxonomy woocommerce

在 woocommerce 中,我使用此答案线程中的代码,将“销售”产品类别分配给正在销售的产品(因此具有有效的销售价格)

当产品不再促销时,我尝试删除“促销”产品类别,但没有成功。当产品不再促销时,是否可以自动将其从“促销”类别中删除?

Loi*_*tec 5

当产品不再促销时,以下版本代码将自动从“促销”类别中删除产品:

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' );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

相关:将“促销”产品类别添加到 Woocommerce 中促销的产品中