Skip to content

Instantly share code, notes, and snippets.

@benhuson
Last active May 20, 2016 19:01
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 benhuson/77fe5ff5a29aba95f332d41b7cc3305d to your computer and use it in GitHub Desktop.
Save benhuson/77fe5ff5a29aba95f332d41b7cc3305d to your computer and use it in GitHub Desktop.
All Category Post Permalink
<?php
/**
* All Category Post Permalink
*
* When using %category% in permalinks, this allows you to substitute
* an alternative slug "all" to replace the category. By default this
* is not permitted - the post page is force redirected to a URL
* with a valid category.
*/
class All_Category_Post_Permalink {
/**
* Constructor
*/
public function __construct() {
add_filter( 'post_link_category', array( $this, 'post_link_category' ), 3, 3 );
}
/**
* Post Link Category
*
* @param WP_Term $cat Category object.
* @param array $cats Post categories.
* @param WP_Post $post Post object.
* @return string Replacement slug for %category% placeholder.
*/
public function post_link_category( $cat, $cats, $post ) {
if ( is_main_query() && ( ( is_home() ) || ( is_single() && $this->get_slug() == get_query_var( 'category_name' ) ) ) ) {
$cat->slug = $this->get_slug();
}
return $cat;
}
/**
* Get "all" Slug
*
* @return string Slug to replace the %category% placeholder if no category.
*/
private function get_slug() {
return sanitize_html_class( apply_filters( 'all_category_post_permalink_slug', 'all' ) );
}
}
new All_Category_Post_Permalink();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment