mehrshaddarzi
5/6/2018 - 5:54 AM

RestApi Wordpress

RestApi Wordpress

<?php

/* Word with Nounce */
$params = array(
  'ajaxurl' => admin_url('admin-ajax.php', $protocol),
  'ajax_nonce' => wp_create_nonce('any_value_here'),
);
wp_localize_script( 'my_blog_script', 'ajax_object', $params );


add_filter( 'nonce_life', function () { return 4 * HOUR_IN_SECONDS; } );
var _nonce = "<?php echo wp_create_nonce( 'wp_rest' ); ?>";
$.ajax({
    type: 'POST',
    url: url_path + '/foo/v1/newbee',
    data: {
        bid : next
    },
    dataType: 'json',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', _nonce );
    }
});
check_ajax_referer( 'wp_rest', '_nonce', false )




add_filter( 'rest_url_prefix', 'buddydev_api_slug');
function buddydev_api_slug( $slug ) {
    return 'api';
	//Please Flush After
}


add_action( 'rest_api_init', 'wp_rest_allow_all_cors', 15 );
function wp_rest_allow_all_cors() {
	// Remove the default filter.
	remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );

	// Add a Custom filter.
	add_filter( 'rest_pre_serve_request', function( $value ) {
		header( 'Access-Control-Allow-Origin: *' );
		header( 'Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE' );
		header( 'Access-Control-Allow-Credentials: true' );
		return $value;
	});
}


/*
 * Disable the WP REST API

add_filter( 'rest_authentication_errors', 'ultimatewoo_disable_rest_api' );
function ultimatewoo_disable_rest_api( $access ) {
	return new WP_Error( 'rest_disabled', __( 'The REST API on this site has been disabled.' ), array( 'status' => rest_authorization_required_code() ) );
} */


// remove all default endpoint
add_filter('rest_endpoints', function( $endpoints ) {

    foreach( $endpoints as $route => $endpoint ){
        if( false !== stripos( $route, '/wp/' ) ){
            unset( $endpoints[ $route ] );
        }
    }

    return $endpoints;
});


//remove custom point rest_api_init
add_filter( 'rest_endpoints', function( $endpoints ){
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
        unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
    }
    return $endpoints;
});


//is rest api check
function is_rest() {
    return ( defined( 'REST_REQUEST' ) && REST_REQUEST );
}


//add auth for add request before
///wp/v2/cards
///wp/v2/cards/(?P<id>[\d]+)
///wp/v2/cards/...possibly some other patterns...

add_filter( 'rest_dispatch_request', function( $dispatch_result, $request, $route, $hndlr )
{
    $target_base = '/wp/v2/cards';    // Edit to your needs

    $pattern1 = untrailingslashit( $target_base ); // e.g. /wp/v2/cards
    $pattern2 = trailingslashit( $target_base );   // e.g. /wp/v2/cards/

    // Target only /wp/v2/cards and /wp/v2/cards/*
    if( $pattern1 !== $route && $pattern2 !== substr( $route, 0, strlen( $pattern2 ) ) )
        return $dispatch_result;

    // Additional permission check
    if( is_user_logged_in() )  // or e.g. current_user_can( 'manage_options' )
        return $dispatch_result;

    // Target GET method
    if( WP_REST_Server::READABLE !== $request->get_method() ) 
        return $dispatch_result;

    return new \WP_Error( 
        'rest_forbidden', 
        esc_html__( 'Sorry, you are not allowed to do that.', 'wpse' ), 
        [ 'status' => 403 ] 
    );

}, 10, 4 );

//where we target the /wp/v2/cards and /wp/v2/cards/* GET routes, with additional user permission checks.
	

//Get params
function my_awesome_func( WP_REST_Request $request ) {
    // You can access parameters via direct array access on the object:
    $param = $request['some_param'];

    // Or via the helper method:
    $param = $request->get_param( 'some_param' );

    // You can get the combined, merged set of parameters:
    $parameters = $request->get_params();

    // The individual sets of parameters are also available, if needed:
    $parameters = $request->get_url_params();
    $parameters = $request->get_query_params();
    $parameters = $request->get_body_params();
    $parameters = $request->get_default_params();

    // Uploads aren't merged in, but can be accessed separately:
    $parameters = $request->get_file_params();
}



//helper Url
https://1fix.io/blog/2016/03/19/wp-api-remove-fields-listing-only/
https://1fix.io/blog/2015/12/12/more-tag-wp-api/
https://1fix.io/blog/2015/12/18/single-request-category-posts/
https://1fix.io/blog/2015/06/26/adding-fields-wp-rest-api/