PHP code example of aivec / wordpress-router

1. Go to this page and download the library: Download aivec/wordpress-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/ */

    

aivec / wordpress-router example snippets


use Aivec\WordPress\Routing\Router;
use Aivec\WordPress\Routing\WordPressRouteCollector;

// First, we declare our routes by extending the `Router` class:
class Routes extends Router {

    /**
     * This is where we define each route
     */
    public function declareRoutes(WordPressRouteCollector $r) {
        $r->addPublicRoute('GET', '/hamburger', function () {
            return 'Here is a public hamburger.';
        });
    }
}

// Next, we instantiate the `Routes` class with a unique namespace and listen for requests
$routes = new Routes('/mynamespace');
$routes->dispatcher->listen();

use Aivec\WordPress\Routing\Router;
use Aivec\WordPress\Routing\WordPressRouteCollector;

// First, extend the `Router` class:
class Routes extends Router {

    /**
     * This is where we define each route
     */
    public function declareRoutes(WordPressRouteCollector $r) {
        /**
         * `add` is the default way to register a route with nonce verification
         */
        $r->add('POST', '/hamburger', function () {
            return 'Here is a private hamburger.';
        });
    }
}


$routes = null;
add_action('init', function () use ($routes) {
    $routes = new Routes('/mynamespace', 'nonce-key', 'nonce-name');
    $routes->dispatcher->listen();
});


add_action('wp_enqueue_scripts', function () use ($routes) {
    wp_enqueue_script(
        'my-script',
        site_url() . '/wp-content/plugins/my-plugin/my-script.js',
        [],
        '1.0.0',
        false
    );

    wp_localize_script('my-script', 'myvars', $routes->getScriptInjectionVariables());
});

$r->add('POST', '/hamburger/{burgername}', function (array $args) {
    return 'Here is a ' . $args['burgername'] . ' hamburger.';
});

$r->add('POST', '/hamburger/{burgername}/{count}', function (array $args) {
    return 'Here are ' . $args['count'] . ' ' . $args['burgername'] . ' hamburgers.';
});

// Matches /user/42, but not /user/xyz
$r->add('POST', '/user/{id:\d+}', .....);

// Matches /user/foobar, but not /user/foo/bar
$r->add('GET', '/user/{name}', .....);

// Matches /user/foo/bar as well
$r->add('GET', '/user/{name:.+}', .....);

// $payload contains the decoded JSON key-value array
$r->add('POST', '/hamburger', function (array $args, array $payload) {
    $ingredients = join(' and ', $payload['ingredients']);
    return 'I want ' . $ingredients . ' on my hamburger.';
});