So I understand for the most part how the wp rest controller works, what it is doing and why it is the best way to do it. The trouble I am having is wrapping my head around the regular expressions in the endpoint URL for the function register_rest_route.

Regular expressions are what they are but I was wondering if someone could break it down for me in this context.

Some example code

register_rest_route( $this->namespace, "https://wordpress.stackexchange.com/" . $this->resource_name . '/(?P<id>[\d]+)', array(
        // Notice how we are registering multiple endpoints the 'schema' equates to an OPTIONS request.
        array(
            'methods'   => 'GET',
            'callback'  => array( $this, 'get_item' ),
            'permission_callback' => array( $this, 'get_item_permissions_check' ),
        ),
        // Register our schema callback.
        'schema' => array( $this, 'get_item_schema' ),
    ) );

So the (?P<id>[\d]+) confuses me a bit I understand it means that the parameter of id is required but what if I wanted multiple parameters and what if wanted to have a route that was something like /vendor/v1/geolocate/{param}/{param} or /vender/v1/?id={param}&address={param}

1 Answer
1

I have the same problem, i search on google finally with the help of the above answer i found out the solution. this may help others.

$this->base = home
register_rest_route( 

        $namespace, "https://wordpress.stackexchange.com/" . $this->base . "https://wordpress.stackexchange.com/" .  'products' . "https://wordpress.stackexchange.com/", array(
            array( 
                'methods'   => WP_REST_Server::READABLE, 
                'callback'  => array( $this, 'rest_api_popular_products'), 
            ),
        )  
    );        
    register_rest_route(
        $namespace, "https://wordpress.stackexchange.com/" . $this->base . "https://wordpress.stackexchange.com/" .  'products' . '/(?P<category>[\d]+)/(?P<sort>[\w]+)', array(
            'args'   => array(
                'id' => array(
                    'description' => __( 'Unique identifier for the resource.', 'woocommerce' ),
                    'type'        => 'integer',
                ),
            ),
            array(
                'methods'             => WP_REST_Server::READABLE,
                'callback' => array( $this, 'rest_api_popular_products' ),                  
                'args'                => array(
                    'context' => $this->get_context_param( array( 'default' => 'view' ) ),
                ),
            )
        )
    );

API request like : ..wp-json/wc/v2/home/products/?category=89&sort=popularity

Leave a Reply

Your email address will not be published. Required fields are marked *