shshanker
8/7/2015 - 7:39 AM

Remove Category base name from urlre

Remove Category base name from urlre

<?php
// remove category base
add_action( 'init', 'change_category_base' );

add_filter( 'rewrite_rules_array', 'create_category_rules' );

function change_category_base( $args ){
        global $wp_rewrite, $wp_taxonomies;
        //change rewrite slug value for the taxonomy
        if( isset( $wp_taxonomies['product_cat'] ) )
            $wp_taxonomies['product_cat']->rewrite['slug'] = '';

        if( isset( $wp_rewrite->extra_permastructs['product_cat'] ) ){
            if( array_key_exists( 'struct', $wp_rewrite->extra_permastructs['product_cat'] ) ) $wp_rewrite->extra_permastructs['product_cat']['struct'] = '%product_cat%';
            else $wp_rewrite->extra_permastructs['product_cat']['0'] = '%product_cat%';
        }
}


function create_category_rules($rules){

        //These rules are generated from changing the product category base to nothing and conflict with wordpress pages
        unset( $rules['(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$'] );
        unset( $rules['(.+?)/(feed|rdf|rss|rss2|atom)/?$'] );
        unset( $rules['(.+?)/page/?([0-9]{1,})/?$'] );
        unset( $rules['(.+?)/?$'] );

        //Generate rules for each product category
        $args = array( 'hide_empty' => 0 );
        $categories = get_terms( 'product_cat', $args );

        $category_rules = array();
        foreach( $categories as $category ){

            $link = str_ireplace(site_url("/"), "", rtrim(get_term_link($category), "/"));

            $category_rules["($link)/feed/(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?product_cat=$matches[1]&feed=$matches[2]';
            $category_rules["($link)/(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?product_cat=$matches[1]&feed=$matches[2]';
            $category_rules["($link)/page/?([0-9]{1,})/?$"] = 'index.php?product_cat=$matches[1]&paged=$matches[2]';
            $category_rules["($link)/?$"] = 'index.php?product_cat=$matches[1]';

        }

        $rules = $category_rules + $rules;


    return $rules;
}
?>