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

How to add a category programmatically to a WooCommerce product?

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_cat', $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', $term_name, 'product_cat' )->term_id;

仅通过 'Sold out' 产品类别术语名称的术语 ID,如 (将 19 替换为实际术语 ID):

$term_id = 19;