I want to create a custom slug in WordPress and output JSON. How do I do this?

You can use pre_get_posts as suggested but simply check the global $wp object for the request url.. like so:

add_action( 'pre_get_posts', function ($query ){
    global $wp;

    if ( !is_admin() && $query->is_main_query() ) {
        if ($wp->request == 'cats'){
            header('Content-Type: application/json');
            $cats = array('Hobbes', 'Simba', 'Grumpy Cat');
            echo json_encode($cats);
            exit;
        }
    }
});

(PHP 5.3+ in this example)

Note 1: The $query->is_main_query() test is important as it will prevent it from running again in subsequent context of WP_Query instances (eg. if you use a WP_Query to fetch your list of cats, you will end up with an infinite nested loop). is_admin() isn’t critical but it’s a good practice to use.

Note 2: WordPress seems to trim trailing slashes in request so this works for /cats & /cats/ the same way

Note 3: You must exit; in your handler otherwise it will keep executing the regular wordpress workflow and likely show a 404 page.

Leave a Comment