Last active
May 20, 2016 19:01
-
-
Save benhuson/77fe5ff5a29aba95f332d41b7cc3305d to your computer and use it in GitHub Desktop.
All Category Post Permalink
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
<?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