WooCommerce 文档

title: "设置 API" post_status: publish comment_status: open taxonomy: category: - woocommerce post_tag: - Settings And Config - Extensions - Repos


设置 API

WooCommerce 设置 API 用于扩展程序显示、保存和加载设置。 在您的扩展程序中使用 API 的最佳方法是创建一个类,该类继承自 WC_Settings_API 类:

class My_Extension_Settings extends WC_Settings_API {
    //
}

定义表单字段

您可以使用类构造函数中的 init_form_fields 方法来定义您的字段:

$this->init_form_fields();

在加载设置之前,您必须定义您的设置。 设置定义应放在 form_fields 数组中:

/**
 * 初始化网关设置表单字段。
 */
function init_form_fields() {
    $this->form_fields = array(
        'title'       => array(
            'title'       => __( 'Title', 'your-text-domain' ),
            'type'        => 'text',
            'description' => __( 'This controls the title which the user sees during checkout.', 'your-text-domain' ),
            'default'     => __( 'PayPal', 'your-text-domain' )
        ),
        'description' => array(
            'title'       => __( 'Description', 'your-text-domain' ),
            'type'        => 'textarea',
            'description' => __( 'This controls the description which the user sees during checkout.', 'your-text-domain' ),
            'default'     => __( "Pay via PayPal; you can pay with your credit card if you don't have a PayPal account", 'your-text-domain' )
        )
    );
} // End init_form_fields()

(请确保您的类初始化 form_fields 属性,以避免在 PHP 8.2+ 中出现“动态属性创建”错误。)

在上面的示例中,我们定义了两个设置:标题和描述。 标题是一个文本框,而描述是一个文本区域。 请注意,您可以为设置本身定义默认值和描述。

设置定义使用以下格式:

'setting_name' => array(
    'title'       => '在设置页面上显示的设置标题',
    'description' => '在设置页面上显示的设置描述',
    'type'        => 'text|password|textarea|checkbox|select|multiselect',
    'default'     => '设置的默认值',
    'class'       => '输入元素的类',
    'css'         => '内联添加到输入元素的 CSS 规则',
    'label'       => '标签', // 仅用于复选框输入。
    'options'     => array( // 仅用于 select/multiselect 输入的选项数组。
        'key' => 'value'
    ),
)

显示您的设置

创建一个名为 admin_options 的方法,其中包含以下内容:

function admin_options() {
    ?>
    <h2<?php esc_html_e( 'Your plugin name', 'your-text-domain' ); ?></h2>
    <table class="form-table">
        <?php $this->generate_settings_html(); ?>
    </table>
    <?php
}

这将以正确的格式输出您的设置。

保存您的设置

为了使您的设置能够保存,请将您类的 process_admin_options 方法添加到适当的 _update_options_ 钩子中。 例如,支付网关应使用支付网关钩子:

add_action( 'woocommerce_update_options_payment_gateways', array( $this, 'process_admin_options' ) );

其他类型的插件具有类似的钩子:

add_action( 'woocommerce_update_options_shipping_methods', array( $this, 'process_admin_options' ) );

加载您的设置

在构造函数中,您可以加载之前定义的设置:

// 加载设置。
$this->init_settings();

之后,您可以从设置 API 加载您的设置。 上述的 init_settings 方法会为您填充设置变量:

// 定义用户设置的变量
$this->title       = $this->settings['title'];
$this->description = $this->settings['description'];