programing

Woocommerce Wordpress - update_post_meta를 사용하여 제품 속성을 추가합니다.

goodjava 2023. 2. 7. 19:58

Woocommerce Wordpress - update_post_meta를 사용하여 제품 속성을 추가합니다.

클라이언트 웹 사이트의 제품에는 Wordpress 관리 페이지에서 Products -> Attributes에서 추가한 특정 속성이 필요합니다.이 Import 스크립트에서는 코딩하고 있습니다.기능을 사용해야 합니다.update_post_meta($post_id, $meta_key, $meta_value)적절한 어트리뷰트와 값을 Import 합니다.

현재 다음과 같은 기능을 가지고 있습니다.

update_post_meta( $post_id, '_product_attributes', array());

하지만 어떻게 속성과 그 값을 제대로 전달해야 할지 모르겠어요.

네, 그래서 제가 직접 알아내는 데 시간이 좀 걸렸지만, 결국 다음 함수를 써서 이 작업을 할 수 있었습니다.

// @param int $post_id - The id of the post that you are setting the attributes for
// @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go
function wcproduct_set_attributes($post_id, $attributes) {
    $i = 0;
    // Loop through the attributes array
    foreach ($attributes as $name => $value) {
        $product_attributes[$i] = array (
            'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
            'value' => $value, // set attribute value
            'position' => 1,
            'is_visible' => 1,
            'is_variation' => 1,
            'is_taxonomy' => 0
        );

        $i++;
    }

    // Now update the post with its new attributes
    update_post_meta($post_id, '_product_attributes', $product_attributes);
}

// Example on using this function
// The attribute parameter that you pass along must contain all attributes for your product in one go
// so that the wcproduct_set_attributes function can insert them into the correct meta field.
$my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size);

// After inserting post
wcproduct_set_attributes($post_id, $my_product_attributes);

// Woohay done!

WooCommerce에서 여러 속성을 프로그래밍 방식으로 Import해야 할 경우 이 기능이 도움이 되었으면 합니다!

대니얼의 대답을 시도해봤지만 소용없었다.그 후 Wordpress/Woocommerce 코드가 바뀌었을 수도 있고, 방법을 잘 몰랐을 수도 있지만, 어느 쪽이든 그 코드는 나에게 아무런 도움이 되지 않았습니다.하지만 그것을 기반으로 많은 작업을 한 후, 나는 이 코드 조각을 생각해 내 테마에 넣었다.functions.php:

function wcproduct_set_attributes($id) {

    $material = get_the_terms( $id, 'pa_material');

    $material = $material[0]->name;

    // Now update the post with its new attributes
    update_post_meta($id, '_material', $material);

}

// After inserting post
add_action( 'save_post_product', 'wcproduct_set_attributes', 10);

이를 통해 WooCommerce 설치에서 "material"로 설정한 것을 커스텀 속성으로 가져와서 _material로 정식 메타에 추가할 수 있습니다.이것에 의해, 다른 코드 조각을 사용할 수 있게 되어, WooCommerce 검색 기능이 메타 필드로 확장됩니다.즉, WooCommerce 검색 필드에서 자료를 검색하여 해당 자료를 가진 모든 항목을 표시할 수 있습니다.

나는 이것이 누군가에게 유용하기를 바란다.

@Daniels의 답변은 유효하지만 옳고 그름을 결정하지는 않지만, 속성 아래에 분류 용어로 값을 추가하려면 다음과 같이 코드를 조정해야 합니다(set is_distern = 1).그렇지 않으면 Woocommerce는 그것을 커스텀메타필드(?)로 인식합니다.Atribute 아래에도 값이 추가됩니다.이것은 문자열에서만 작동합니다.배열 값인 경우 코드를 조정해야 합니다.

또한 @Anand가 제안하는 wp_set_object_terms도 사용합니다.제가 그걸 사용하고 있었어요. 왜냐하면 제가 찾을 수 있는 모든 문서들은 그걸 사용해야 한다고 믿었기 때문이죠.그러나 wp_set_object_terms만 사용하면 제품 편집 화면에서 속성을 볼 수 없습니다.답안과 주제에 대한 읽기 정보를 모두 사용하여 해결했습니다.

제품의 종류 등에 대해서는 코드를 수정해야 합니다.

/*
 * Save Woocommerce custom attributes
 */

function save_wc_custom_attributes($post_id, $custom_attributes) {
    $i = 0;
    // Loop through the attributes array
    foreach ($custom_attributes as $name => $value) {
        // Relate post to a custom attribute, add term if it does not exist
        wp_set_object_terms($post_id, $value, $name, true);
        // Create product attributes array
        $product_attributes[$i] = array(
            'name' => $name, // set attribute name
            'value' => $value, // set attribute value
            'is_visible' => 1,
            'is_variation' => 0,
            'is_taxonomy' => 1
        );
        $i++;
    }
    // Now update the post with its new attributes
    update_post_meta($post_id, '_product_attributes', $product_attributes);
}

그런 다음 함수를 호출합니다.

   $custom_attributes = array('pa_name_1' => $value_1, 'pa_name_2' => $value_2, 'pa_name_3' => $value_3);
   save_wc_custom_attributes($post_id, $custom_attributes);

Daniel & Anand라는 코드를 게시해 주셔서 감사합니다.그것은 나에게 큰 도움이 되었다.

이게 '올바른' 방법인지...그러나 저장 후 속성으로 날짜 값을 가진 ACF 리피터 필드를 추가하는 기능이 필요했기 때문에 다음과 같은 기능을 생각해 냈습니다.

add_action( 'save_post', 'ed_save_post_function', 10, 3 );

function ed_save_post_function( $post_ID, $post, $update ) {
  //print_r($post);
  if($post->post_type == 'product')
    {
     $dates = get_field('course_dates', $post->ID);
     //print_r($dates);
     if($dates)
       {
        $date_arr = array();
        $val = '';
        $i = 0;
        foreach($dates as $d)
               {
                 if($i > 0)
                   {
                    $val .= ' | '.date('d-m-Y', strtotime($d['date']));   
                   }
               else{
                    $val .= date('d-m-Y', strtotime($d['date']));
                   } 
                 $i++;  
               }
            $entry = array(
                           'course-dates' => array(
                                                   'name' => 'Course Dates',
                                                   'value' => $val,
                                                   'position' => '0',
                                                   'is_visible' => 1,
                                                   'is_variation' => 1,
                                                   'is_taxonomy' => 0
                                                  )
                          );
                update_post_meta($post->ID, '_product_attributes', $entry);
       }
    }
}

이게 도움이 됐으면 좋겠네요.

언급URL : https://stackoverflow.com/questions/23444319/wordpress-woocommerce-use-update-post-meta-to-add-product-attributes