首頁  >  問答  >  主體

如果產品未設置,則在儲存時新增屬性:WooCommerce

儲存產品時,我想檢查該產品是否具有特定屬性。就我而言,pa_region。如果沒有,我想將屬性集和屬性術語新增到產品中。 如果屬性 pa_region 已設置,我不想更新/更改它。

我看到有一個名為 wp_set_object_terms 的函數(文件)。我嘗試了一些方法,但我認為 update_post_meta 是正確的方法。

從這個答案我知道如何檢查產品是否具有屬性。我稍後會添加該檢查。

目前我嘗試先新增該屬性。目前還無法正常運作。

我在這裡發現了類似的問題,我嘗試使用該程式碼來達到我的目的。但這不起作用。我猜原因是該功能需要產品中已有的屬性? ! 編輯:我檢查過。即使在產品中設定了屬性 pa_region,程式碼也不會更新它的值。

這是我目前的程式碼:

add_action('woocommerce_update_product', 'save_product_region');
function save_product_region( $post )
{
    if( in_array( $post->post_type, array( 'product' ) ) ){

        $test = 'test';
        $product_id = $post->ID;

        $product_attributes = get_post_meta( $product_id ,'_product_attributes', true);
        var_dump($product_attributes);

        // Loop through product attributes
        foreach( $product_attributes as $attribute => $attribute_data ) {
            // Target specif attribute  by its name
            if( 'pa_region' === $attribute_data['name'] ) {
                // Set the new value in the array
                $product_attributes[$attribute]['value'] = $test;
                break; // stop the loop
            }
        }

        update_post_meta( $product_id ,'_product_attributes', $product_attributes );

    }
}

P粉555682718P粉555682718285 天前452

全部回覆(1)我來回復

  • P粉520204081

    P粉5202040812023-12-14 10:05:21

    第一個 $post 不是物件。將返回 ID,這很好。

    add_action('woocommerce_update_product', 'save_product_region');
    function save_product_region( $product_id ) {
    
        //Get product object from the ID
        $_product = wc_get_product($product_id);
        $attributes = $_product->get_attributes();
    
        $add_option = wp_set_object_terms( $product_id, 'canada', 'pa_region', true );
        $curr_options = $attributes['pa_region']['options'];
        
        //Check if we have this attribute set already 
        if(!in_array($add_option,$curr_options)):
            $updated_options = array_push($curr_options,$add_option);
            $data = array(
                'pa_region' => array(
                    'name'=>'pa_region',
                    'options'=> $updated_options,
                    'is_visible' => '1',
                    'is_variation' => '0',
                    'is_taxonomy' => '1'
                )
            );
            //First getting the Post Meta
            $_product_attributes = get_post_meta($product_id, '_product_attributes', TRUE);
            //Updating the Post Meta
            update_post_meta($product_id, '_product_attributes', array_merge($_product_attributes, $data));
        endif;
    }

    回覆
    0
  • 取消回覆