Custom Endpoint Gives 404 Header

I’m not sure if this is the only reason why it wasn’t working but I was missing two things.

  1. I wasn’t added any sort of rewrite rule to test on
  2. I was testing against pagename instead of query_vars.

Here’s the final solution:

/** Register Query Vars **/
function theme_custom_query_vars( $vars ){
    $vars[] = 'map';
    return $vars;
}
add_filter( 'query_vars', 'theme_custom_query_vars' );

/** Register Endpoint **/
function theme_register_endpoints() {
    add_rewrite_rule( '^map/?', 'index.php?map=map', 'top' );
    add_rewrite_endpoint( 'map', EP_PERMALINK );
}
add_action( 'init', 'theme_register_endpoints' );

/** Give Endpoint a Template **/
function endpoint_map_template( $templates="" ){
    global $wp_query;
    $template = $wp_query->query_vars;

    if ( array_key_exists( 'map', $template ) && 'map' == $template['map'] ) {
        include( get_template_directory().'/page-templates/template-map.php' );
        exit;
    }
}
add_filter( 'template_redirect', 'endpoint_map_template' );

Leave a Comment