WPBP / WordPress-Plugin-Boilerplate-Powered

Wordpress Plugin Boilerplate but Powered with examples and a generator!
https://wpbp.github.io/
GNU General Public License v3.0
791 stars 114 forks source link

[BUG] Add register rest example #206

Closed Mte90 closed 2 years ago

Mte90 commented 2 years ago

As today this is missing.

Mte90 commented 2 years ago
$('#subscribe-exa').on('click', function() {
                $.ajax({
                    method: "POST",
                    url: window.subscribe_exa.domain + "wp-json/example/subscribe-exa",
                    data: {
                        nonce: window.subscribe_exa.nonce,
                        user: window.subscribe_exa.user
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-WP-Nonce', window.subscribe_exa.wp_rest);
                    }
                })
                .done(function( msg ) {
                    window.location.reload();
                }).fail(function( msg ) {
                    alert( "Qualcosa non ha funzionato" );
                });
        });
register_rest_route(
            'example', 'subscribe-exa', array(
            'methods' => 'POST',
            'args' => array(
            'user' => array(
                    'required' => true,
            ),
            'nonce' => array(
            'required' => true,
            )
            ),
            'callback' => array( $this, 'subscribe_exa' ),
            'permission_callback' => '__return_true'
            )
        );
public function subscribe_lottery( \WP_REST_Request $request )
    {
        if (!wp_verify_nonce($request['nonce'], 'exa_nonce') ) {
            $response = rest_ensure_response('Wrong nonce');
            $response->set_status(500);
            return $response;
        }

        $response = rest_ensure_response('User is not allowed');
        $response->set_status(500);
        return $response;
    }
wp_localize_script(
                PN_TEXTDOMAIN . '-script',
                PN_TEXTDOMAIN . '_variables',
                array(
                    'nonce'  => wp_create_nonce( 'exa_nonce' ),
                    'domain'  => get_site_url() . '/',
                    'wp_rest' => wp_create_nonce( 'wp_rest' ),
                )
            );