自动为 Woocommerce 上购买的产品设置特定属性术语值

2023-12-06

我想在下订单并处于“暂停”状态时自动向订购的产品添加特定的属性值(之前设置)。

我销售独特的产品,并且我设置了“STOCK”属性和“Out Of Stock”(缺货)值。

当下订单并处于“暂停”状态时,我想自动更改订购产品的特色状态,并向其添加缺货属性值。

特色部分已完成并有效,但我不知道如何向产品添加特定的属性值。

这是我的代码:

add_action('woocommerce_order_status_on-hold', 'order_status_on_hold_update_products', 20, 2);

function order_status_on_hold_update_products( $order_id, $order ) {
  foreach ( $order->get_items() as $item_id => $item ) {
    $product = $item->get_product();
    $product->set_featured(true);
    $product->set_attributes(???); // I don't know if and how set_attributes() should be used
    $product->save();
}

要设置库存状态“缺货”,您将使用WC_Product method set_stock_status()这边走:

 $product->set_stock_status('outofstock'); // Or "instock"
 $product->save();

在挂钩函数中设置产品属性术语(也适用于可变产品):

add_action('woocommerce_order_status_on-hold', 'order_status_on_hold_update_products', 20, 2);
function order_status_on_hold_update_products( $order_id, $order ) {
    foreach ( $order->get_items() as $item_id => $item ) {
        $product = $item->get_product();

        // Handling variable products
        $_product = $product->is_type('variation') ? wc_get_product( $item->get_product_id() ) : $product;

        $_product->set_featured( true );

        // Your product attribute settings
        $taxonomy   = 'pa_stock'; // The taxonomy
        $term_name  = "Out Of Stock"; // The term

        $attributes = (array) $_product->get_attributes();
        $term_id    = get_term_by( 'name', $term_name, $taxonomy )->term_id;

        // 1) If The product attribute is set for the product
        if( array_key_exists( $taxonomy, $attributes ) ) {
            foreach( $attributes as $key => $attribute ){
                if( $key == $taxonomy ){
                    $attribute->set_options( array( $term_id ) );
                    $attributes[$key] = $attribute;
                    break;
                }
            }
            $_product->set_attributes( $attributes );
        }
        // 2. The product attribute is not set for the product
        else {
            $attribute = new WC_Product_Attribute();

            $attribute->set_id( sizeof( $attributes) + 1 );
            $attribute->set_name( $taxonomy );
            $attribute->set_options( array( $term_id ) );
            $attribute->set_position( sizeof( $attributes) + 1 );
            $attribute->set_visible( true );
            $attribute->set_variation( false );
            $attributes[] = $attribute;

            $_product->set_attributes( $attributes );
        }

        $_product->save();

        // Append the new term in the product
        if( ! has_term( $term_name, $taxonomy, $_product->get_id() ) )
            wp_set_object_terms($_product->get_id(), $term_slug, $taxonomy, true );
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中。它应该有效。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

自动为 Woocommerce 上购买的产品设置特定属性术语值 的相关文章