Skip to content

Instantly share code, notes, and snippets.

@LinzardMac
Created March 31, 2017 18:44
Show Gist options
  • Save LinzardMac/f5e25c9b89e40034770a78ff87b56171 to your computer and use it in GitHub Desktop.
Save LinzardMac/f5e25c9b89e40034770a78ff87b56171 to your computer and use it in GitHub Desktop.
Better "verbose" rewrite rules for pages?
/**
* Verbose rewrite rules are required when there is a potential conflict between the slug of a page and the slug of
* another content type like a post type.
*
* WordPress needs to know first and foremost that they do not need to seek out a page when the front portion of a url
* has a value that matches the 'rewrite slug' of a CPT.
* We can avoid this by building the page rewrite rules to specifically ignore all instances where these match with the
* below code:
**/
function ignore_cpts_as_pages($rules){
//filter to override and make your own list to force ignore
$slugs_list = apply_filters('exclude_slugs_for_pages');
if(empty($slugs_list)){
$args = array(
'public' => true,
'publicly_queryable' => true,
'rewrite' => true //not sure if this is valid. Goal is to check if 'rewrite' has a value, not that it's value is true
);
$cpts = get_post_types( $args, 'objects', '' );
//filter to allow customing, cleaning, or altering the list of CPT slugs
$slugs_list = apply_filters('exclude_cpt_slugs_for_pages', $cpts);
}
// build the list to ignore
foreach($cpts as $cpt){
$slug_to_ignore = $cpt->rewrite['slug'];
$appended .= '(?!'.$slug_to_ignore.')';
}
$new_rules = array();
foreach($rules as $k => $v){
$new_rules[$appended.$k] = $v;
}
return $new_rules;
}
/**
* The resulting rules will look like the below regex
* where the slug for each CPT is a negative lookahead appended to the beginning
* of the standard page rewrite rule
*
*
* ~^/(?!events)(?!features)(?!sites)(?!galleries)(?!back\-issues)(.?.+?)(?:/([0-9]+))?/?$~
*
* /something/42346/ <~~ page query
* /events/something/42346/ <~~ ignore page query
* /features/sdomg/woies <~~ ignore page query
* /something/sdlfisdf <~~ page query
*
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment