Forked from mikeschinkel/root-based-category-urls.php
Last active
February 8, 2023 01:39
-
-
Save PatelUtkarsh/6651acbfa428d2630b011c860230650b to your computer and use it in GitHub Desktop.
Enabled Root-based Category URLs in WordPress (Any bugs? Post comments below.)
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 | |
/* | |
* Plugin Name: Root-based Category URLs | |
* Description: Enables root-based Category URLs, i.e. Makes /category/my-category/ URLs route as /my-category/ | |
* Author: Mike Schinkel | |
* Author URI: http://about.me/mikeschinkel | |
* Plugin URI: https://gist.github.com/1421235 | |
* Version: 0.1.1 | |
*/ | |
class Rootbased_Category_URLs { | |
function on_load() { | |
add_filter( 'request', [ $this, 'request' ] ); | |
add_filter( 'category_link', [ $this, 'category_link' ] ); | |
} | |
function request( $query_vars ) { | |
global $wp; | |
if ( preg_match( '#' . self::get_category_base() . '(.*)#', $wp->request, $match ) ) { | |
wp_safe_redirect( self::category_link( $wp->request ), 301 ); | |
exit; | |
} | |
$term = get_term_by( 'slug', $wp->request, 'category' ); | |
// $category_hash = array_flip( self::get_category_slugs() ); | |
// if ( isset( $category_hash[ $wp->request ] ) ) { | |
// $query_vars = [ 'category_name' => $wp->request ]; | |
// } | |
if ( $term instanceof WP_Term ) { | |
$query_vars = [ 'category_name' => $wp->request ]; | |
} | |
return $query_vars; | |
} | |
function get_category_base() { | |
$category_base = get_option( 'category_base' ); | |
if ( empty( $category_base ) ) { | |
$category_base = 'category'; | |
} | |
return "/{$category_base}/"; | |
} | |
function category_link( $category_link ) { | |
return str_replace( self::get_category_base(), '/', $category_link ); | |
} | |
function get_category_slugs() { | |
$categories = get_categories(); | |
foreach ( $categories as $index => $category ) { | |
$categories[ $index ] = $category->slug; | |
} | |
return $categories; | |
} | |
} | |
$root_cat = new Rootbased_Category_URLs(); | |
$root_cat->on_load(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment