Skip to content

Instantly share code, notes, and snippets.

@matgargano
Created August 27, 2015 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matgargano/77048dfc3e29fabffc7c to your computer and use it in GitHub Desktop.
Save matgargano/77048dfc3e29fabffc7c to your computer and use it in GitHub Desktop.
rewrites for all taxonomy combinations
<?php
function eg_add_rewrite_rules() {
global $wp_rewrite;
$post_type = 'post';
if ( ! is_object( $post_type ) ) {
$post_type = get_post_type_object( $post_type );
}
$new_rewrite_rules = array();
$taxonomies = get_object_taxonomies( $post_type->name, 'objects' );
unset( $taxonomies['post_format'] );
$all_combinations = get_permutations( array_keys( $taxonomies ) );
foreach ( $all_combinations as $tmp ) {
if ( count( $tmp ) > 1 ) {
$new_all_combinations[] = $tmp;
}
}
foreach ( $new_all_combinations as $combination ) {
$counter = 0;
$rule = $rewrite = '';
foreach ( $combination as $item ) {
$query_var = $taxonomies[ $item ]->query_var;
$counter ++;
$rule .= $item . '/(.+?)/';
$prefix = 'index.php?';
if ( $rewrite ) {
$prefix = '&';
}
$rewrite .= $prefix . $query_var . '=matches[' . $counter . ']';
}
if ( $rule ) {
$new_rewrite_rules = array_merge( array( $rule . '?$' => $rewrite ), $new_rewrite_rules );
}
}
$wp_rewrite->rules = $new_rewrite_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );
function get_permutations( array $values ) {
$n = count( $values );
$rec = function ( array $values, &$ret, $n, array $cur = array() ) use ( &$rec ) {
if ( $n > 0 ) {
foreach ( $values as $v ) {
$newCur = $cur;
if ( ! in_array( $v, $newCur ) ) {
$newCur[] = $v;
}
$rec( $values, $ret, $n - 1, $newCur );
}
} else {
$ret[] = $cur;
}
};
$ret = array();
$rec( $values, $ret, $n );
$combination_permutation = array_filter( array_unique( $ret, SORT_REGULAR ) );
//sort array by number of elements
usort( $combination_permutation, function ( $a, $b ) {
if ( $a == $b ) {
return 0;
}
return ( count( $a ) > count( $b ) ) ? - 1 : 1;
} );
return $combination_permutation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment