Created
November 4, 2017 00:59
-
-
Save ammist/ab30db0a1868ffa632eccc5f6a8870bd to your computer and use it in GitHub Desktop.
Taxonomy/Post URL Rewrite rule example for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function my_rewrite_rules( $rules_array ) { | |
$new = array(); | |
//get the list of categories and create a rewrite rules for each. | |
// We get them in order by parent so that we can quickly build the array we need. | |
$cats = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => false, 'hierarchical' => true, 'fields' => 'all', 'orderby' => 'parent')); | |
// extract the parents and build the array for generating the rules | |
$cr = array(); | |
foreach ($cats as $c) { | |
$cr[$c->term_id] = array('slug' => $c->slug, 'rewrite' => 2); | |
} | |
// set up the children that will be rewritten. | |
foreach($cats as $c){ | |
if ( $c->parent != 0 || $c->slug === 'archive' || $c->slug === 'other-languages') { | |
// $cr[$c->term_id] = array( 'slug' => $cr[$c->parent]['slug'] . '/' . $c->slug, 'rewrite' => 1); | |
$cr[$c->term_id] = array( 'slug' => $c->slug, 'rewrite' => 1); | |
} | |
} | |
foreach ($cr as $c){ | |
if ($c['rewrite'] == 1) { | |
$match = '^' . $c['slug'] . '/(.+)?$'; | |
$new[$match] = 'index.php?cpt_slug=$matches[1]'; | |
} | |
} | |
return array_merge( $new, $rules_array ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment