Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Created May 12, 2014 21:58
Show Gist options
  • Save danielbachhuber/c1554c1777dbb0460bfb to your computer and use it in GitHub Desktop.
Save danielbachhuber/c1554c1777dbb0460bfb to your computer and use it in GitHub Desktop.
Serve a subset of terms at /term-slug instead of /tag/term-slug
<?php
/**
* 'special-term' is a unique butterfly
*/
function dbx_get_special_terms() {
return array( 'special-term' );
}
/**
* Update our special terms' term links
*/
add_filter( 'term_link', function( $termlink, $term, $taxonomy ) {
global $wp_rewrite;
if ( 'post_tag' !== $taxonomy ) {
return $termlink;
}
if ( in_array( $term->slug, dbx_get_special_terms() ) ) {
$tag_base = get_option( 'tag_base' );
if ( empty( $tag_base ) ) {
$tag_base = 'tag';
}
$termlink = str_replace( "/{$tag_base}/", "/", $termlink );
}
return $termlink;
}, 10, 3 );
/**
* Custom URI structures need custom rewrite rules
*/
add_action( 'init', function() {
$special_terms_string = implode( '|', dbx_get_special_terms() );
add_rewrite_rule( '^(' . $special_terms_string . ')/feed/(feed|rdf|rss|rss2|atom)/?$', 'index.php?tag=$matches[1]&feed=$matches[2]', 'top' );
add_rewrite_rule( '^(' . $special_terms_string . ')/(feed|rdf|rss|rss2|atom)/?$', 'index.php?tag=$matches[1]&feed=$matches[2]', 'top' );
add_rewrite_rule( '^(' . $special_terms_string . ')/page/?([0-9]{1,})/?$', 'index.php?tag=$matches[1]&paged=$matches[2]', 'top' );
add_rewrite_rule( '^(' . $special_terms_string . ')/?$', 'index.php?tag=$matches[1]', 'top' );
});
/**
* Canonical redirect for our special terms
* Resolves /tag/special-terms/ to /special-terms/
*/
add_action( 'template_redirect', function() {
if ( ! is_tag() ) {
return;
}
if ( ! in_array( get_queried_object()->slug, dbx_get_special_terms() ) ) {
return;
}
$tag_base = get_option( 'tag_base' );
if ( empty( $tag_base ) ) {
$tag_base = 'tag';
}
if ( 0 !== stripos( $_SERVER['REQUEST_URI'], '/tag/' ) ) {
return;
}
wp_safe_redirect( get_term_link( get_queried_object() ) );
exit;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment