I’m working on rewrite rules for a plugin that uses a URL endpoint, /modifier, to create a query_var &modifier=1 to signify it should do something else.

The rewrite deals with URLs where /modifier is appended to the end of a URL for a post, page, or custom post type.

It seems like adding a rewrite endpoint would be ideal, but according to the WordPress rewrite endpoints API the incoming URL would need to end with a value, like /modifier/1 in order to rewrite automatically to &modifier=1 via the endpoint API. If there’s no value after the endpoint, it resolves to &modifier= and has no value when checking if it isset.

So I’m still doing it the long way, via generate_rewrite_rules. The rewrite for posts and pages works fine - I could include it but maybe it’s not relevant.

The rewrite for custom post types, added at the top, also works when a post type is explicitly hardcoded.

add_filter('generate_rewrite_rules', 'my_rewrite');
function my_rewrite($wp_rewrite) {
    // rewrite rules for custom post type "specific-type"
    $cpt_rules = array(
        'specific-type-slug/([^/]+)/modifier' => 'index.php?specific-type='. $wp_rewrite->preg_index(1) .'&modifier=1'
    );
    $wp_rewrite->rules = $cpt_rules + $wp_rewrite->rules;
}

The problem is making a loop for all custom post types. get_post_types() is only available after init. This rewrite is filtering generate_rewrite_rules, several steps earlier.

So here’s the loop I’ve tried. It obviously doesn’t work, the post types aren’t set up yet.

add_filter('generate_rewrite_rules', 'my_rewrite');
function my_rewrite($wp_rewrite) {
  global $wp_post_types;
  $types = get_post_types( array( '_builtin' => false ) );
  // get the registered data about each post type with get_post_type_object
  foreach( $types as $type ) {
    $cpt_rules = '';
    $typeobj = get_post_type_object( $type );
    if( isset( $typeobj->rewrite->slug ) ) {
        $slug = $typeobj->rewrite->slug;
        $cpt_rules = array(
            $slug.'/([^/]+)/modifier' => 'index.php?'.$type.'='. $wp_rewrite->preg_index(1) .'&modifier=1'
        );
        $wp_rewrite->rules = $cpt_rules + $wp_rewrite->rules;
    }
  }
}

Something tells me using a plugin class might be the way to solve this, but I don’t understand how.

Read more here: Rewrite Endpoints and CPTs - How to use in a plugin


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , ,

Wordpress related questions and answers: