Magic Fields (custom post types) and Custom Taxonomy permalink

I’m using Custom Post Template which I linked to Magic Fields to create custom post type named Company.
I also created custom taxonomy named City.
City is hierarchical (like categories), and every Company has one city selected.

For example:
I have a company with post title Microsoft and City taxonomy Redmond selected.
I want my permalinks to look like this:
http://www.mysite.com/Redmond/Microsoft

Read More

Just like when you have a post category and wordpress prepends first category selected to your permalink.
Can it be done?

Related posts

Leave a Reply

2 comments

  1. I’ve found solution to this problem. Here is the code:

    add_filter('post_link', 'mba_courses_permalink', 10, 3);
    add_filter('post_type_link', 'mba_courses_permalink', 10, 3);
    
    function mba_courses_permalink($permalink, $post_id, $leavename) {
        if (strpos($permalink, '%mba_courses%') === FALSE) return $permalink;
    
        // Get post
        $post = get_post($post_id);
        if (!$post) return $permalink;
    
        // Get taxonomy terms
        $terms = wp_get_object_terms($post->ID, 'mba_courses'); 
        if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
        else $taxonomy_slug = 'mba_courses';
    
    return str_replace('%mba_courses%', $taxonomy_slug, $permalink);
    }