如何以编程方式向WooCommerce产品添加类别?

问题描述

WooCommerce中,如果某商品售罄,我想为其添加一个类别“售罄”,以便可以在单独的部分中显示这些商品。

我在WooCommerce / WordPress“管理”面板中创建了“售罄”类别。

这就是我的functions.php中的内容:

add_action( 'woocommerce_before_shop_loop_item_title','mytheme_display_sold_out_loop_woocommerce' );
 
function mytheme_display_sold_out_loop_woocommerce() {
    global $product;
 
    if ( !$product->is_in_stock() ) {
       // add category "sold out"   
    }
}

现在,如何将“已售出”类别自动添加到任何售罄的WooCommcerce产品中?

解决方法

假设存在产品类别术语名称“已售完”,请尝试以下操作:

add_action( 'woocommerce_before_shop_loop_item_title','mytheme_display_sold_out_loop_woocommerce' );
 
function mytheme_display_sold_out_loop_woocommerce() {
    global $product;

    $term_name = 'Sold out';

    // Get the product category term Id for "Sold out" term name
    $term_id   = get_term_by( 'name',$term_name,'product_cat' )->term_id;
 
    // 1. Add product category "Sold out"
    if ( ! $product->is_in_stock() && ! has_term( $term_id,'product_cat',$product->get_id() ) ) {
       // Get product categories (if there is any)
       $term_ids = (array) $product->get_category_ids();

       // Add the product category term Id for "Sold out" term name to $term_ids array
       $term_ids[] = $term_id;

       $product->set_category_ids( $term_ids ); // Update product categories
       $product->save(); // Save to database
    } 
    // 2. Remove product category "Sold out"
    elseif ( $product->is_in_stock() && has_term( $term_id,$product->get_id() ) ) {
       // Get product categories (if there is any)
       $term_ids = (array) $product->get_category_ids();

       // Remove the product category term Id for "Sold out" term name in $term_ids array
       if ( ( $key = array_search( $term_id,$term_ids ) ) !== false ) {
           unset($term_ids[$key]);
       }

       $product->set_category_ids( $term_ids ); // Update product categories
       $product->save(); // Save to database
    }
}

代码进入活动子主题(或活动主题)的functions.php文件中。应该可以。


现在,将术语“ id”用于“售罄”产品类别应该更轻松了,因此您可以用这种方式替换(在代码中)

$term_name = 'Sold out';

// Get the product category term Id for "Sold out" term name
$term_id   = get_term_by( 'name','product_cat' )->term_id;

仅按“售罄”产品类别术语名称的术语ID(如(用真实术语ID替换 19

$term_id = 19; 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...