在 Woocommerce 中以编程方式创建新的产品属性

Create new product attribute programmatically in Woocommerce

如何从插件中为 WooCommerce 创建属性? 我只找到:

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

来自this stack-question

但是这种方法需要某些产品的 ID。我需要生成一些未附加到任何产品的属性。

要创建术语,您可以使用 wp_insert_term()

像这样:

wp_insert_term( 'red', 'pa_colors' );

其中 colors 是您的属性的名称。属性的分类法名称始终以 pa_.

为前缀

编辑 属性只是自定义分类法。或者您可以说它们是由用户在后端手动创建的动态分类法。尽管如此,自定义分类法规则仍然适用。

您可以在每个上看到 source code here which loops through the attributes and runs register_taxonomy()。因此,要创建一个新属性(记住它只是一个分类法),那么您需要 运行 register_taxonomy() 并简单地将 pa_ 添加到分类法名称的开头。

从核心中模仿分类法参数的某些值将为您提供类似这样的 '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 数据库 table 中。从那里 WooCommerce 运行s register_taxonomy() 在 table 中找到的每一个。因此,为了创建属性分类法,应向此 table 添加一行。 WooCommerce 有一个函数 wc_create_attribute() 可以为我们处理这个问题。 (自 3.2+ 起)。

我测试属性是否存在的条件逻辑不是最好的,我建议在插件的更新例程中使用某种版本选项。但作为使用 wc_create_taxonomy() 的示例,这应该插入一个名为“我的颜色”的属性。

/**
 * 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' );

For 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 文件。已测试并有效。


基于:

Related: