如何从插件中为 WooCommerce 创建属性? 我只发现:
wp_set_object_terms( $object_id, $terms, $taxonomy, $append);
但这种方法需要某些产品的 ID。我需要生成一些不附加到任何产品的属性。
最佳答案
要创建术语,您可以使用 wp_insert_term()
像这样:
wp_insert_term( 'red', 'pa_colors' );
其中 colors
是您的属性名称。属性的分类法名称始终以 pa_
为前缀。
编辑 属性只是自定义分类法。或者您可以说它们是由用户在后端手动创建的动态分类法。尽管如此,自定义分类法规则仍然适用。
你可以看到 source code here它循环遍历属性并运行 register_taxonomy()
在各个。因此,要创建一个新属性(记住它只是一个分类法),您需要运行 register_taxonomy()
并将 pa_
简单地添加到分类法名称的开头。
从核心中模仿分类法参数的一些值将为“颜色”属性得到类似这样的东西。
/**
* 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 有一个功能 wc_create_attribute()
那将为我们处理这个。 (自 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' );
关于php - 在 Woocommerce 中以编程方式创建新的产品属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29549525/