0

I have a custom post type called "menu" with the following categories

  • hotboxes
  • salads
  • soups
  • wraps

Code:

register_taxonomy(
    'menutype',
    array("menu"),
    array(
        "hierarchical" => true, 
        "label" => "Menu Categories", 
        "singular_label" => "Menu Category", 
        "rewrite" => array( 'slug' => 'menu/type', 'hierarchical'=>'true'), 
        "show_ui"=>"radio", // used a plugin
        "query_var" => true
    )
);

Right now if I want to say, show all my "hotboxes" it goes to

http://www.mysite.com/menu/type/hotboxes

But if it shows an individual hotbox it just goes to

http://www.mysite.com/menu/hotbox-single-item

Is there a way to rewrite the url so it says

http://www.mysite.com/menu/type/hotbox/hotbox-single-item

The ideal format I am looking for is:

http://www.mysite.com/custom_post_type/custom_taxonomy/post_name

EDIT: I managed to get the link looking like the way I wanted by doing:

function menu_post_link( $post_link, $id = 0 ) {

        $post = get_post($id);

        if ( $post->post_type != 'menu')
        {
            return $post_link;  
        }

        if( $terms = wp_get_object_terms( $post->ID, 'menutype' ) ) {
            $custom_taxonomy = $terms[0]->slug;
            $post_link = str_replace('menu', 'menu/'.$custom_taxonomy, $post_link);
        }


        return $post_link;

    }
    add_filter( 'post_type_link', 'menu_post_link', 10, 2 );

Note: My custom post type is called "menu" and my custom taxonomy is called "menutype".

This now creates the permalink I want:

http://www.mysite.com/custom_post_type/custom_taxonomy/post_name

However it generates a 404 error even after flushing my rewrite rules (Settings > Permalinks > save)

1

Try something similar to this:

function custom_rewrite( $wp_rewrite ) {
    $feed_rules = array(
        '(.+)/([^/]+)(/[0-9]+)?/?$'    =>  'index.php?post_type='.$wp_rewrite->preg_index(1).'&custom_taxonomy='. $wp_rewrite->preg_index(2).'&post_name='. $wp_rewrite->preg_index(3)
    );

    $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
}
// refresh/flush permalinks in the dashboard if this is changed in any way
add_filter( 'generate_rewrite_rules', 'custom_rewrite' );

You may need to modify the regex, as regex isn't one of my strongpoints, and you'll need to swap out your taxonomy name in the URL. You may want to hardcode the custom post type too and adjust the rest accordingly to avoid clashes.

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.