More gentle way to hook WordPress custom url

So it seems you want to leave it as a late as possible before setting what WordPress should return (in certain circumstances – e.g. when sitemap.xml is being requested).

There are two methods – which are broadly identical – but using the WordPress API do varying degrees.

The same principal applies to almost any content format (JSON, ICAL etc) and not just XML

Method 1: Add a feed:

Benefits of this is that WordPress immediately ‘recognizes’ the request. Unfortunately, it leaves you with ‘feed’ in the url – which you may/may not be desirable. For ICAL calendars, for instance, I think this method works well;

add_action('init','eventorganiser_public_export');
function eventorganiser_public_export(){
    add_feed('wpse73174', 'wpse73174_content_callback');    
}

Then the output is determined by wpse73174_content_callback() and is available at www.example.com/feed/wpse73174/ (depending on permalinks).

Method 2: Manual approach

A bit more ‘hands on’ is to use to redirect_template action. It’s up to you here to decide if the query is for the content you are about to serve:

add_action('template_redirect','maybe_wpse73174_content_callback');
function maybe_wpse73174_content_callback(){
   if( /* we are after this content */ ){
         wpse73174_content_callback();
   }
}

The problem here is now deciding whether the user is requesting your content. You’ll need to add your own rewrite rules / permastructures and query variables to recognize the query. (For JSON content its quite nice to add an endpoint). You might find these articles written by me at WP.Tuts relevant.

The callback

The callback function wpse73174_content_callback() is require to set the headers (if appropriate), print the content and then exit();

function wpse73174_content_callback(){
  echo 'Hello World';
  exit();
}