要实现在 WooCommerce » Settings » Pages 下添加自定义选项,例如添加一个选择产品分类的功能,如下图所示

代码如下
add_filter( 'WooCommerce_page_settings', 'wc_multi_country_fields' );
add_action( 'WooCommerce_admin_field_single_select_category', 'wc_single_select_category' );
add_action( 'WooCommerce_update_option', 'wc_save_single_select_category' );
function wc_multi_country_fields( $settings ){
$new = array();
foreach( $settings as $setting ){
if( $setting['id'] == 'WooCommerce_shop_page_id' ){
$new[] = $setting;
$new[] = array(
'title' => __('Base category', 'venus'),
'desc' => __('Select the base category', 'venus'),
'id' => 'WooCommerce_base_category_page_id',
'type' => 'single_select_category',
'default' => '',
'class' => 'chosen_select_nostd',
'css' => 'min-width:300px;',
'desc_tip' => true
);
} else {
$new[] = $setting;
}
}
return $new;
}
function wc_single_select_category( $value ){
global $WooCommerce;
$tip = '<img class="help_tip" data-tip="' . esc_attr( $value['desc'] ) . '" src="'%20.%20$WooCommerce->plugin_url()%20.%20'/assets/images/help.png" height="16" width="16" />';
$args = array(
'name' => $value['id'],
'id' => $value['id'],
'orderby' => 'name',
'order' => 'ASC',
'show_option_none' => ' ',
'class' => $value['class'],
'echo' => false,
'hide_empty' => false,
'taxonomy' => 'product_cat',
'selected' => absint(WooCommerce_settings_get_option($value['id']))
);
if (isset($value['args']))
$args = wp_parse_args($value['args'], $args);
?><tr valign="top" class="single_select_page">
<th scope="row" class="titledesc"><?php echo esc_html($value['title']) ?> <?php echo $tip; ?></th>
<td class="forminp">
<?php echo str_replace(' id=', " data-placeholder='" . __('Select a category…', 'venus') . "' style='" . $value['css'] . "' class'] . "' id=", wp_dropdown_categories($args)); ?> <?php echo $description; ?>
</td>
</tr><?php
}
function wc_save_single_select_category( $value ){
if( $value['type'] == 'single_select_category'){
if ( isset( $_POST[$value['id']] ) ) {
$option_value = WooCommerce_clean( stripslashes( $_POST[ $value['id'] ] ) );
} else {
$option_value = '';
}
update_option( $value['id'], $option_value );
}
}
调用所保存的 category 方法
WooCommerce 的产品分类是一个 custom taxonomy,slug 是 product_cat
获取产品分类 ID
WooCommerce_get_page_id('base_category')
获取产品分类链接
get_term_link( (int)WooCommerce_get_page_id('base_category'), 'product_cat' )