Make WordPress Core

Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#49255 closed defect (bug) (invalid)

It is not possible to register field for settings endpoint.

Reported by: vavra7's profile vavra7 Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.7
Component: REST API Keywords: needs-patch
Focuses: rest-api Cc:

Description

Function register_rest_field() does not work for endpoint settings. Here is example code which is supposed to work but it doesn't. No field is added.

Used WordPress v5.3.2. No plugins.

<?php
function add_field_show_on_front()
{
        $args = [
                'get_callback' => function() {
                        return get_option('show_on_front');
                }
        ];

        register_rest_field('setting', 'show_on_front', $args);
}

add_filter('rest_api_init', 'add_field_show_on_front');

Change History (2)

#1 @TimothyBlynJacobs
5 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed
  • Version changed from 5.3.2 to 4.7

Hi @vavra7,

Thanks for the ticket! This is intended behavior, if you want to add a setting to the settings controller, you should register the option using register_setting and setting show_in_rest to true.

For instance:

<?php
register_setting(
        'writing',
        'default_category',
        array(
                'show_in_rest' => true,
                'type'         => 'integer',
                'description'  => __( 'Default post category.' ),
        )
);

#2 @vavra7
5 years ago

Aha, I see now!

So this is what I need:

<?php
function register_custom_settings()
{
        $args = array(
                'type' => 'string',
                'default' => get_option('show_on_front'),
                'show_in_rest' => true,
        );
        register_setting('custom_settings', 'show_on_front', $args);
        
}
add_action('rest_api_init', 'register_custom_settings');

Thank you @TimothyBlynJacobs

Note: See TracTickets for help on using tickets.