WooCommerce Single Category Selector
优质
小牛编辑
132浏览
2023-12-01
要实现在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="' . $woocommerce->plugin_url() . '/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='" . $value['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' )