WooCommerce

WooCommerce设置 – 自定义选项卡和字段(2021)

WooCommerce的设置指仪表盘 - WooCommerce - 设置下的选项卡,有常规、产品、配送等等。很多WooCommerce插件会在这里增加自己的设置选项,它们是怎么做的呢?本文将介绍向WooCommerce设置里添加自定义选项卡和字段的方法。

WooCommerce设置 - 自定义选项卡和字段

WooCommerce设置 – 向产品设置里添加自定义选项卡和字段

目标:如上图所示,在产品选项卡下添加Example Section,里面就写一个简单的字段吧,主要看一看字段的存储和读取。

首先,告诉WooCommerce我们要添加一个新的选项卡。代码如下,放在子主题的functions.php里。

add_filter( 'woocommerce_get_sections_products', 'sola_new_product_section' );
function sola_new_product_section( $sections ) {
  
  $sections['sola_new_section'] = 'Example Section';
  return $sections;
  
}

然后,添加标题和一个简单的text字段

add_filter( 'woocommerce_get_settings_products', 'sola_new_section_settings', 10, 2 );
function sola_new_section_settings( $settings, $current_section ) {

  if ( $current_section == 'sola_new_section' ) {
    
    $settings = array(
      array(
        'name' => 'Example Settings',
        'type' => 'title',
        'desc' => 'This is an example Settings',
        'id'   => 'sola_new_section'
      ),
      array(
        'name'     => 'A text field',
        'id'       => 'custom_field_name',
        'type'     => 'text',
        'desc_tip' => 'The tips',
        'desc'     => 'Descriptions',
        'css'      => 'min-width:300px;',
      ),
      array(
        'type' => 'sectionend',
        'id'   => 'sola_new_section'
      ),
    );
    return $settings;
  
  }
}

效果如下图所示:

如何读取保存的字段数据

数据保存由WooCommerce接管,我们不用操心,数据会存储到wp_options表中,读取就用:

get_option('custom_field_name')

如何向其它选项卡下添加字段

这个filter的形式是:woocommerce_get_sections_{tab_name},对应关系如下

  • 常规 – woocommerce_get_settings_general
  • 产品 – woocommerce_get_settings_products
  • 配送 – woocommerce_get_settings_shipping
  • 付款 – woocommerce_get_settings_checkout
  • 账户和隐私 – woocommerce_get_settings_account
  • 电子邮件 – woocommerce_get_settings_email
  • 高级 – woocommerce_get_settings_advanced

参考文章:Adding a Section to a Settings Tab