source

Woocommerce에서 프로그래밍 방식으로 새 제품 특성 생성

factcode 2023. 2. 13. 20:50
반응형

Woocommerce에서 프로그래밍 방식으로 새 제품 특성 생성

플러그인에서 WooCommerce 속성을 만들려면 어떻게 해야 합니까?다음 항목만 검색:

wp_set_object_terms( $object_id, $terms, $taxonomy, $append);

이 스택 질문에서

그러나 이 방법에는 일부 제품의 ID가 필요합니다.어떤 제품에도 부착되지 않은 속성을 생성해야 합니다.

사용할 수 있는 항을 만드는 방법

다음과 같이 합니다.

wp_insert_term( 'red', 'pa_colors' );

어디에colors는 Atribute 이름입니다.Atribute의 분류법 이름 앞에는 항상 다음과 같은 이름이 붙습니다.pa_.

속성 편집은 사용자 지정 분류에 불과합니다.또는 사용자가 백엔드에서 수동으로 작성하는 동적 분류법이라고 할 수 있습니다.그래도 모두 동일한 사용자 정의 분류 규칙이 적용됩니다.

여기서 Atribute를 루프하여 각각에서 실행되는 소스 코드를 볼 수 있습니다.코드를 확인할 수 있습니다.따라서 새로운 Atribute를 작성하려면(이것은 단순한 분류법임을 기억하십시오)register_taxonomy()간단한 프리펜드pa_분류법 이름의 선두에 표시됩니다.

core에서 분류 arg의 값 중 일부를 모방하면 'Colors' 속성의 경우와 같은 결과를 얻을 수 있습니다.

/**
 * Register a taxonomy.
 */
function so_29549525_register_attribute() {

    $permalinks = get_option( 'woocommerce_permalinks' );

    $taxonomy_data = array(
                        'hierarchical'          => true,
                        'update_count_callback' => '_update_post_term_count',
                        'labels'                => array(
                                'name'              => __( 'My Colors', 'your-textdomain' ),
                                'singular_name'     => __( 'Color', 'your-textdomain' ),
                                'search_items'      => __( 'Search colors', 'your-textdomain' ),
                                'all_items'         => __( 'All colors', 'your-textdomain' ),
                                'parent_item'       => __( 'Parent color', 'your-textdomain' ),
                                'parent_item_colon' => __( 'Parent color:', 'your-textdomain' ),
                                'edit_item'         => __( 'Edit color', 'your-textdomain' ),
                                'update_item'       => __( 'Update color', 'your-textdomain' ),
                                'add_new_item'      => __( 'Add new color', 'your-textdomain' ),
                                'new_item_name'     => __( 'New color', 'your-textdomain' )
                            ),
                        'show_ui'           => false,
                        'query_var'         => true,
                        'rewrite'           => array(
                            'slug'         => empty( $permalinks['attribute_base'] ) ? '' : trailingslashit( $permalinks['attribute_base'] ) . sanitize_title( 'colors' ),
                            'with_front'   => false,
                            'hierarchical' => true
                        ),
                        'sort'              => false,
                        'public'            => true,
                        'show_in_nav_menus' => false,
                        'capabilities'      => array(
                            'manage_terms' => 'manage_product_terms',
                            'edit_terms'   => 'edit_product_terms',
                            'delete_terms' => 'delete_product_terms',
                            'assign_terms' => 'assign_product_terms',
                        )
                    );

  register_taxonomy( 'pa_my_color', array('product'), $taxonomy_data );

}
add_action( 'woocommerce_after_register_taxonomy', 'so_29549525_register_attribute' );

업데이트 2020-11-18

아트리뷰트 분류법은{$wpdb->prefix}woocommerce_attribute_taxonomies데이터베이스 테이블거기서부터 WooCommerce가 실행됩니다.register_taxonomy()각 테이블에서 찾을 수 있습니다.따라서 속성 분류법을 작성하려면 이 테이블에 행을 추가해야 합니다.WooCommerce는 이 문제를 해결할 수 있는 기능이 있습니다(3.2 이후).

속성이 존재하는지 테스트하기 위한 저의 조건부 논리는 가장 훌륭하지 않습니다.따라서 플러그인 업데이트 루틴에 버전 옵션을 사용하는 것이 좋습니다.단, 예를 들어wc_create_taxonomy()그러면 "My Color"라는 속성이 삽입됩니다.

/**
 * Register an attribute taxonomy.
 */
function so_29549525_create_attribute_taxonomies() {

    $attributes = wc_get_attribute_taxonomies();

    $slugs = wp_list_pluck( $attributes, 'attribute_name' );

    if ( ! in_array( 'my_color', $slugs ) ) {

        $args = array(
            'slug'    => 'my_color',
            'name'   => __( 'My Color', 'your-textdomain' ),
            'type'    => 'select',
            'orderby' => 'menu_order',
            'has_archives'  => false,
        );

        $result = wc_create_attribute( $args );

    }
}
add_action( 'admin_init', 'so_29549525_create_attribute_taxonomies' );

Woocommerce 3+(2018)의 경우

레이블 이름에서 새 제품 속성을 생성하려면 다음 기능을 사용합니다.

function create_product_attribute( $label_name ){
    global $wpdb;

    $slug = sanitize_title( $label_name );

    if ( strlen( $slug ) >= 28 ) {
        return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
    } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
        return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
    } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
        return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
    }

    $data = array(
        'attribute_label'   => $label_name,
        'attribute_name'    => $slug,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0, // Enable archives ==> true (or 1)
    );

    $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );

    if ( is_wp_error( $results ) ) {
        return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
    }

    $id = $wpdb->insert_id;

    do_action('woocommerce_attribute_added', $id, $data);

    wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );

    delete_transient('wc_attribute_taxonomies');
}

코드가 기능합니다.php 파일에는 액티브한 아이 테마(또는 활성 테마).테스트 및 동작.


기준:

관련: Woocommerce 3에서 CRUD 메서드를 사용하여 프로그래밍 방식으로 제품 생성

언급URL : https://stackoverflow.com/questions/29549525/create-new-product-attribute-programmatically-in-woocommerce

반응형