有没有办法在Woocommerce中向添加新属性页面或编辑属性添加自定义字段?
最好使用CMB2,但无论什么都可以。
据我所知,woocommerce的这一特定部分是一个分类法的开端——它是一个创建分类法的分类法:)我查看了woocommerce/includes/class wc帖子类型。php,但不确定什么过滤器会起作用(如果有的话)。
我已经设法将字段添加到各个术语中,但我需要为属性本身添加一个字段。
有没有办法在Woocommerce中向添加新属性页面或编辑属性添加自定义字段?
最好使用CMB2,但无论什么都可以。
据我所知,woocommerce的这一特定部分是一个分类法的开端——它是一个创建分类法的分类法:)我查看了woocommerce/includes/class wc帖子类型。php,但不确定什么过滤器会起作用(如果有的话)。
我已经设法将字段添加到各个术语中,但我需要为属性本身添加一个字段。
是的,您可以向WooCommerce(product)属性添加自定义字段,这些属性是WordPress自定义分类法-例如,名为Color的属性使用slug创建分类法pa_color
.
但是因为数据存储在the woocommerce_attribute_taxonomies
table 它不提供自定义数据字段,您需要将数据保存在其他地方,例如WordPress选项表(wp_options
) 就像我在下面的例子中所做的那样:
function my_edit_wc_attribute_my_field() {
$id = isset( $_GET[\'edit\'] ) ? absint( $_GET[\'edit\'] ) : 0;
$value = $id ? get_option( "wc_attribute_my_field-$id" ) : \'\';
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="my-field">My Field</label>
</th>
<td>
<input name="my_field" id="my-field" value="<?php echo esc_attr( $value ); ?>" />
</td>
</tr>
<?php
}
add_action( \'woocommerce_after_add_attribute_fields\', \'my_edit_wc_attribute_my_field\' );
add_action( \'woocommerce_after_edit_attribute_fields\', \'my_edit_wc_attribute_my_field\' );
function my_save_wc_attribute_my_field( $id ) {
if ( is_admin() && isset( $_POST[\'my_field\'] ) ) {
$option = "wc_attribute_my_field-$id";
update_option( $option, sanitize_text_field( $_POST[\'my_field\'] ) );
}
}
add_action( \'woocommerce_attribute_added\', \'my_save_wc_attribute_my_field\' );
add_action( \'woocommerce_attribute_updated\', \'my_save_wc_attribute_my_field\' );
add_action( \'woocommerce_attribute_deleted\', function ( $id ) {
delete_option( "wc_attribute_my_field-$id" );
} );
然后,例如,在分类法/术语归档页面上,您可以获得如下所示的“我的字段”值:$term = get_queried_object();
$attr_id = wc_attribute_taxonomy_id_by_name( $term->taxonomy );
$my_field = get_option( "wc_attribute_my_field-$attr_id" );