Создайте новый атрибут продукта программно в Woocommerce


Как я могу создать атрибуты для WooCommerce из плагина? Я нахожу только:

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

Из этот стек-вопрос

Но этот подход требовал идентификатора некоторого продукта. Мне нужно сгенерировать некоторые атрибуты, не привязанные ни к каким продуктам.

Author: LoicTheAztec, 2015-04-10

2 answers

Для создания термина вы можете использовать wp_insert_term()

Вот так:

wp_insert_term( 'red', 'pa_colors' );

Где colors - имя вашего атрибута. Имя таксономии атрибута всегда предваряется pa_.

Редактировать Атрибуты - это просто пользовательские таксономии. Или вы могли бы сказать, что это динамические таксономии, которые вручную создаются пользователем в серверной части. По-прежнему применяются все те же правила пользовательской таксономии.

Вы можете увидеть исходный код здесь, который циклически через атрибуты и запуски register_taxonomy() на каждом. Поэтому, чтобы создать новый атрибут (помните, что это всего лишь таксономия), вам нужно запустить register_taxonomy() и просто добавить pa_ в начало имени таксономии.

Имитируя некоторые значения аргументов таксономии из ядра, вы получите нечто подобное для атрибута "Цвета".

add_action( 'woocommerce_after_register_taxonomy', 'so_29549525_register_attribute' );

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'              => 'Colors',
                                'singular_name'     => 'Color',
                                'search_items'      => sprintf( __( 'Search %s', 'woocommerce' ), $label ),
                                'all_items'         => sprintf( __( 'All %s', 'woocommerce' ), $label ),
                                'parent_item'       => sprintf( __( 'Parent %s', 'woocommerce' ), $label ),
                                'parent_item_colon' => sprintf( __( 'Parent %s:', 'woocommerce' ), $label ),
                                'edit_item'         => sprintf( __( 'Edit %s', 'woocommerce' ), $label ),
                                'update_item'       => sprintf( __( 'Update %s', 'woocommerce' ), $label ),
                                'add_new_item'      => sprintf( __( 'Add New %s', 'woocommerce' ), $label ),
                                'new_item_name'     => sprintf( __( 'New %s', 'woocommerce' ), $label )
                            ),
                        '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_colors', array( 'product' ) ), $taxonomy_data );

}
 9
Author: helgatheviking, 2017-10-26 14:13:50

Для 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');
}

Вводится код function.php файл вашей активной дочерней темы (или активной темы). Проверено и работает.


На основе:

 1
Author: LoicTheAztec, 2018-09-04 00:24:09