将默认选项保存为选项数组并在REST API中显示

时间:2021-08-27 作者:Badan

我正在尝试保存选项数组并在rest api中显示它们。我知道我可以用register_setting, 但我认为在一个数组中保存所有选项比单独保存每个选项要好,因为它将只是一个请求,而不是四个不同的请求。然而,我得到的回应是awg_settings: null

$general_options = [
    \'is_show_post\'     => true,
    \'is_show_page\'    => true,
    \'is_show_cpt\'      => \'\',
    \'featured_post_id\' => \'\',
];

// register plugin options
add_option( \'awg_settings\', $general_options );

register_setting(
    \'awg_option_fields\',
    \'awg_settings\',
    [
        \'show_in_rest\' => true,
        \'type\'         => \'array\',
    ]
);


    componentDidMount() {
        // fetch all plugin options
        api.loadPromise.then(() => {
            this.settings = new api.models.Settings();
            const { isAPILoaded } = this.state;

            if (!isAPILoaded) {
                this.settings.fetch().then((response) => {
                    console.log(response);
                });
            }
        });
}

1 个回复
SO网友:Badan

由于这个答案,我解决了这个问题:Serialized settings in rest api.

我能够将所有选项存储为json对象:

/**
 * Create plugin options schema as an object and prepare it for the rest api. 
 * WP >=5.3
 */
function my_register_settings() {

    $general_options = [
        \'show_in_rest\' => [
            \'schema\' => [
                \'type\'       => \'object\',
                \'properties\' => [
                    \'is_show_post\'     => [
                        \'type\'    => \'string\',
                        \'default\' => \'true\',
                    ],
                    \'is_show_page\'     => [
                        \'type\'    => \'string\',
                        \'default\' => \'true\',
                    ],
                    \'is_show_cpt\'      => [
                        \'type\'    => \'string\',
                        \'default\' => \'\',
                    ],
                    \'featured_post_id\' => [
                        \'type\'    => \'string\',
                        \'default\' => \'\',
                    ],
                ],
            ],
        ],
    ];

    // register plugin options as an object
    register_setting(
        \'awg_settings\',
        \'awg_options\',
        $general_options
    );

}

add_action( \'init\', \'my_register_settings\' );