0

I am trying to save array of options and display them in the rest api. I know I can store the options one by one with register_setting, but I think saving all the options in an array is better than saving each option individually, since it will be just one request instead of four different requests. However, the response I get is 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

I solved the issue thanks to this answer: Serialized settings in rest api.

I was able to store all the options as a json object:

/**
 * 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' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.