1. Go to this page and download the library: Download x-wp/ajax-router library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
x-wp / ajax-router example snippets
use Sunrise\Http\Router\Exception\PageNotFoundException;
use XWP\Decorator\Core\Controller;
use XWP\Decorator\Core\Use_Guards;
use XWP\Decorator\HTTP\Argument\Body;
use XWP\Decorator\HTTP\Get;
use XWP\Decorator\HTTP\Param;
use XWP\Decorator\HTTP\Post;
use XWP\Guard\Capability_Guard;
use XWP\Guard\Nonce_Guard;
use XWP\Response\JSON;
#[Use_Guards( new Nonce_Guard() )]
#[Controller( 'my-endpoint' )]
class My_Controller {
#[Get( 'get-post/{id}', JSON::class )]
public function get_post( #[Param( 'id' )]
int $id, ): \WP_Post {
return \get_post( $id );
}
#[Use_Guards( new Capability_Guard( 'manage_options' ) )]
#[Post( 'modify-post/{id}', JSON::class )]
public function modify_post( #[Param( 'id' )] int $id, #[Body] array $data ): int {
$post = \get_post( $id );
if ( ! $post ) {
throw new PageNotFoundException( 'Invalid post', 404 );
}
return wp_update_post(
array_merge(
array( 'ID' => $id ),
$data,
),
);
}
}