Rewrite Endpoints and CPTs – How to use in a plugin

Apologies if this seemed too obvious to answer, i’m just getting my head around htaccess rewrites in wordpress.

The most elegant way to parse the modifier through the URL like this seems to be to add a rewrite endpoint and just check for it in the URL later, if you don’t want to pass a value.

The beauty is there’s no need for any other rewrite rules, as long as you’re just checking for this endpoint.

add_action( 'init', 'wp_modifier_endpoint' );
function wp_modifier_endpoint() {
    add_rewrite_endpoint( 'modifier', EP_PERMALINK | EP_PAGES );
}

In the function creating the /modifier links, there’s also no need to add a value after /modifier/value either, unless you need a value. My previous technique checked if the endpoint (as query_var) isset, but you can just check for the endpoint string within the URL with the php strrpos function.

$url="http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
$endpoint = substr( $url, 9 ); /* number of chars in string "/modifier" */
if( false !== strpos( $endpoint, '/modifier' ) ) {
    /* do something; */
}

Update: per Milo’s comment below, it is preferable to check if modifier is an array_key of query_vars – this seems more foolproof and easily extensible, in case you want to check for multiple keys.

global $wp_query;
if( array_key_exists( 'modifier' , $wp_query->query_vars ) ) {
    /* do your thing; */
}