how do i create a specific handler for a url?

I want to create an image generator that will use a url like : /image-generator?a=1b=2c=3

The image generator will be dynamic and create an image based on the params. It will also output the image. So there will be no HTML and the header will return content-type: image/jpg.

What's the best way to achieve this? I looked into creating a custom route, but apparently you're not supposed to do that. Do I need to create a custom type and a post and set a custom handler for that type? How can I make it go straight to code and skip all the templates?

Topic routing custom-post-types Wordpress

Category Web


You could use the parse_request hook. For example:

add_action( 'parse_request', function ( $wp ) {
    // Run your actions only if the current request path is exactly 'image-generator'
    // as in https://example.com/image-generator if the site URL is https://example.com
    if ( 'image-generator' === $wp->request ) {
        $a   = $_GET['a'];
        $b   = $_GET['b'];
        $etc = 'etc';
        // ... your code here.

        // And then send the HTTP status and also the Content-Type headers.
        status_header( 200 );
        header( 'Content-Type: image/jpeg' );
        // ... echo your image.

        exit;
    }
} );

And note that status_header() is a WordPress function for sending HTTP status header. See the documentation for more details.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.