添加“销售" Woocommerce中销售的产品的产品类别 [英] Adding "Sale" product category to products that are on sale in Woocommerce

查看:128
本文介绍了添加“销售" Woocommerce中销售的产品的产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为WooCommerce网站的一部分,我希望有一个销售页面,其中列出了销售项目(具有分页和过滤功能).我认为最好的方法是将销售"类别自动添加到销售的任何帖子中(因为类别页面允许自动过滤和分页.

As part of a WooCommerce site I want to have a sale page that lists sale items (with pagination and filtering). I think the best way to do this is to have a 'Sale' category that is added automatically to any posts that are part of the sale (as category pages allow for filtering and pagination automatically.

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

I have this code so far to programatically add the sale category to products when you save them:

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

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

但是,我只希望在销售商品(即设置了销售价格)的情况下发生这种情况,这样,保存非销售商品就不会添加销售类别.我尝试了几种不同的方法,但是没有运气.我试过了,但是没用:

However, I only want this to happen if a product is on sale (i.e has sale price set) so that saving posts that are not on sale does not add the sale category. I have tried several different things, but have had no luck. I tried this, but it didnt work:

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

但这只是使我的网站在保存时冻结.

but this just made my site freeze on save.

有什么想法吗?

安迪

推荐答案

已更新2 (2018年10月)

save_post 是WordPress的一个钩子,可与 $post_id 参数一起使用并定位所有类型的帖子.您首先需要在某种情况下(和 publish post_status)定位 product 自定义WooCommerce post_type.

由于它不是发布对象,因此不能使用 is_on_sale() 方法.但是您可以使用 get_post_meta() 功能来检查产品中是否设置了销售价格.

Also as it's not a post object you can't use is_on_sale() method with it. But you can use get_post_meta() function to check if the sale price is set in the product.

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

Here is the fully functional and tested code (for simple products only):

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文件中.经过测试并可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

相关:自动从Woocommerce中的非促销产品中删除促销产品"类别

这篇关于添加“销售" Woocommerce中销售的产品的产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆