Conditionally custom post type url rewrite

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);