1

I am going to try and sum up what I am trying to achieve. I have custom post type named "item" and there are also registered taxonomy named "item_category". I need now to rewrite url, to remove "item" completly from url and instead of that to put "item_category".

"item_category", of course can have different values like food or sport and example would be:

http:sitename.com/item/post_name - > http:sitename.com/food/post_name
http:sitename.com/item/post_name - > http:sitename.com/sport/post_name

So I should check taxonomy (value of "item_category") and replace name of custom post type ("item" in this case) with that taxonomy. I can't register different post types or do any larger code changes because client has theme installed and a lot of content inside, so that option is off.

Is this at all possible?

1

Yes it is possible. One part of my question is answered here and full code I will type here.

I have larger function wich checkes post taxanomy (in this case custom categories for custom post type). Then we check is there particular taxonomy and we change URL structure.


add_filter('post_type_link', 'replace_link', 1, 3);
function replace_link( $link, $post = 0 ){
    //custom post type "item"
    if ( $post->post_type == 'item' ){
            //registered taxonomy for custom post type "item_category"
            $terms = get_the_terms( $post->ID, 'item_category' );

            if ( $terms && ! is_wp_error( $terms ) ) : 
                $links = array();
                //put all taxanomy asigned to that post into one array
                foreach ( $terms as $term ) 
                {
                    $links[] = $term->name;
                }
                $links = str_replace(' ', '-', $links); 

            endif;

            //check if there is particular taxonomy and change URL structure
            if (in_array("Food", $links)) {
                 return home_url('food/'. $post->post_name);            
            }

            if (in_array("Sport", $links)) {
                return home_url('sport/'. $post->post_name);
            }

    } else {
        return $link;
    }
}

Now there are 2 functions because we need corresponding rewrite rules to set the proper query vars for those requests. If there is not those functions we would get 404 page.


function custom_rewrite_rule1() {
   add_rewrite_rule('food/([^/]+)/?$','index.php?item=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule1', 10, 0);

function custom_rewrite_rule2() {
   add_rewrite_rule('sport/([^/]+)/?$','index.php?item=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule2', 10, 0);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.