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

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

The rewrite for posts and pages works fine - I can include it but i don’t think it’s 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: Filtering Rewrite Rules for CPTs - How to get_post_types() before init


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: