将 "Sale" 产品类别添加到 Woocommerce 中销售的产品

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

作为 WooCommerce 网站的一部分,我想要一个列出销售商品的销售页面(具有分页和过滤功能)。我认为最好的方法是有一个 'Sale' 类别自动添加到任何属于销售的帖子(因为类别页面允许自动过滤和分页。

到目前为止,我有这段代码可以在您保存产品时以编程方式将销售类别添加到产品中:

function update_test( $product) { 
wp_set_object_terms($product, 'sale', 'product_cat', true );
}

add_action( 'save_post', 'update_test', 1, 2);`

但是,我只希望在产品打折时发生这种情况(即设置了促销价),以便保存非促销的帖子不会添加促销类别。我尝试了几种不同的方法,但没有运气。我试过了,但没用:

function update_test( $product ) { 
if($product->is_on_sale()){
wp_set_object_terms($product, 'sale', 'product_cat', true );
}
}

add_action( 'save_post', 'update_test', 1, 2);`

但这只是让我的网站在保存时冻结。

有什么想法吗?

安迪

更新 2(2018 年 10 月)

save_post 是一个 WordPress 挂钩,可与 $post_id 参数一起使用并针对所有类型的 post秒。您需要首先在条件中定位 product 自定义 WooCommerce post_type(并且 publish post_status).

此外,由于它不是 post 对象,因此您不能对它使用 is_on_sale() 方法。但是您可以使用get_post_meta()函数来检查产品中是否设置了促销价

这是功能齐全且经过测试的代码(仅适用于简单产品:

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 );
        }
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。 已测试并有效。

相关:Auto remove Sale product category from not on sale products in Woocommerce

我认为更方便的方法是 也适用于可变产品 ,将在子主题的 function.php 中添加以下内容(或通过插件等):

add_action( 'woocommerce_update_product', 'update_product_set_sale_cat', 10, 2 );

function update_product_set_sale_cat( $product_id, $product ) {
    if ( $product->is_on_sale() ) {
        wp_add_object_terms($product_id, "sale", 'product_cat');
    } else { // this will also remove the sale category when the product in no longer on sale
        wp_remove_object_terms($product_id, "sale", 'product_cat');
    }
}

它使用 woocommerce_update_product 挂钩,只要产品在数据库中 updated/created 就会运行。