问题描述
如何通过插件为WooCommerce创建属性?我只找到:
How can I create attributes for WooCommerce from a plugin?I find only :
wp_set_object_terms( $object_id, $terms, $taxonomy, $append);
来自此堆栈问题
但是这种方法需要某些产品的ID.我需要生成一些未附加到任何产品的属性.
But this approach required id of some product. I need to generate some attributes not attached to any products.
推荐答案
要创建术语,可以使用 wp_insert_term()
To create a term you can use wp_insert_term()
像这样:
wp_insert_term( 'red', 'pa_colors' );
其中,colors
是属性的名称.属性的分类名称始终以pa_
开头.
where colors
is the name of your attribute. The taxonomy name of an attribute is always prepended by pa_
.
编辑属性仅仅是自定义分类法.或者,您可以说它们是由用户在后端手动创建的动态分类法.尽管如此,自定义分类规则仍然适用.
Edit Attributes are merely custom taxonomies. Or you could say they are dynamic taxonomies that are manually created by the user in the back-end. Still, all the same, custom taxonomy rules apply.
您可以看到源代码此处的代码,它遍历属性并在每个属性上运行 register_taxonomy()
.因此,要创建一个新的属性(请记住,这只是一个分类法),则需要运行register_taxonomy()
并将简单的pa_
前置在分类法名称的开头.
You can see the source code here which loops through the attributes and runs register_taxonomy()
on each. So to create a new attribute (remember it is just a taxonomy) then you need to run register_taxonomy()
and simple prepend pa_
to the start of the taxonomy name.
从核心中模拟分类法args的某些值将为颜色"属性提供类似的信息.
Mimicking some of the values of the taxonomy args from core would get you something like this for a 'Colors' attribute.
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 );
}
这篇关于在Woocommerce中以编程方式创建新产品属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!