aubreypwd

Aubrey Portwood

Change Sub Category to Main Category URL Structure (WordPress Remove Sub Category Hierarchy URL)

| Permalink

While working on Enjfi, I ran into an undesired feature. When browsing to a sub-category, in WordPress, I ended up with a URL structure like:

[sourcecode]

http://aubreypwd.com/category/sub-category

[/sourcecode]

Now, that usually works. But, with Enjifi, I may want to move sub-category under category-2, like:

[sourcecode]

http://enjifo.com/category-2/sub-category

[/sourcecode]

Now, all my links to /category/sub-category are not /category-2/sub-category, the undesired feature.

So, I found this, and I wrote a plugin for it (because it worked).

sub-cat-to-main-cat.zip

[php wraplines=”true”]
<?php

/*
Plugin Name: Change Sub Category to Main Category URL Structure (WordPress Remove Sub Category Hierarchy URL)
Plugin URI: http://aubreypwd.com/
Description: This plugin will tell your website to remap /category/category/subcategory to /category/subcategory
Version: 0.1
Author: Aubrey Island
Author Email: enethrie@gmail.com
Author URI: http://aubreypwd.com
*/

/* From: http://wordpress.stackexchange.com/questions/7807/changing-the-category-permalink-structure/7817#7817 */

add_filter( ‘category_link’, ‘wpse7807_category_link’, 10, 2 );
function wpse7807_category_link( $catlink, $category_id )
{
global $wp_rewrite;
$catlink = $wp_rewrite->get_category_permastruct();

if ( empty( $catlink ) ) {
$catlink = home_url(‘?cat=’ . $category_id);
} else {
$category = &get_category( $category_id );
$category_nicename = $category->slug;

$catlink = str_replace( ‘%category%’, $category_nicename, $catlink );
$catlink = home_url( user_trailingslashit( $catlink, ‘category’ ) );
}
return $catlink;
}

?>

[/php]