Ever had more than one category assigned to a post? Did you get stuck with a single permalink where you might have wanted a dynamic permalink based on the current category? Read on and find out how to ‘hack’ your WordPress theme to make this happen.
First of all, change your permalink structure to /%category%/%postname%/ Also, may I suggest you install the WP No Category Base plugin? This makes your permalinks very pretty and very readable like so: www.yourwebsite.com/parent-category-name/child-category-name/post-name.
Guess what? The last part of the URL is the slug of your post name, the part before the slash is the slug of the current category! We’re going to use this to write our own permalinks. Trust me .. they’ll work even if WordPress suggest otherwise. You can try this right now if you want to. Go to your website (after installing the plug-in and changing your permalink structure of-course) and type www.yourwebsite.com/that-other-category-you-assigned-to-your-post/the-slug-of-your-post into the address bar. Does it work?
Now on the coding part. I assume you are familiar with coding in PHP and now where your functions.php file is? It’s in the folder of your current theme. Go and and open it. We need to add the following lines of code to this file:
function multiple_category_post_link($url = '') { // check permalink structure for the required construct; /%category%/%postname%/ if (strrpos(get_option('permalink_structure'), '%category%/%postname%') !== false) { // get the current post global $post, $wp_query; // prepare variables for use below $post_id = $cat_id = 0; $new_url = ''; // for categories if (is_category()) { // remember current category and post $cat_id = get_query_var('cat'); $post_id = $post->ID; // add the post slug to the current url $new_url = $_SERVER['REQUEST_URI'] . $post->post_name; } // for single posts else if (is_single()) { // last part in the 'category_name' should be the slug for the current category $cat_slug = array_pop(explode('/', get_query_var('category_name'))); $cat = get_category_by_slug($cat_slug); // remember current category and post $post_id = $wp_query->post->ID; if ($cat) $cat_id = $cat->cat_ID; // replace the slug of the post being viewed by the slug of $post $new_url = str_replace('/' . get_query_var('name'), '', $_SERVER['REQUEST_URI']) . $post->post_name; } if ($post_id > 0 && $cat_id > 0 && !empty($new_url)) { // make sure categories match! foreach(get_the_category($post_id) as $cat) { if ($cat->cat_ID == $cat_id) { $url = $new_url; break; } } } } // always return an url! return $url; } add_filter('post_link', 'multiple_category_post_link');
Save and upload your new functions.php file to your webserver and check out the changes on your website. You can also download the text file with all the code; multiple_category_post_link.txt. Let us know if it worked in the comments below.