3

I'm pretty new to wordpress and I'm trying to create a recipes blog.

I've created a custom taxonomy for ingredients:

register_taxonomy( 
    'ingredient', 
    'post', 
    array( 'label' => 'Ingredient', 
           'hierarchical' => true
         ), 
    array( 'rewrite' => array (
                            'slug'=>'recipes-with'
                        )
    );

Everythings works and my urls are like

www.mysite.com/recipes-with/onion

but I'd like my urls to be like

www.mysite.com/recipes-with-onion

I've tried to look into add_rewrite_rule(), but I can't seem to make it work.

Any help would be greatly appreciated!

EDIT: Here's how I resolved the issue with toni_lehtimaki help, too.

1) I removed the rewrite array in the args argument of register_taxonomy so it became:

register_taxonomy( 'ingredient', 'post', array('label'=>'Ingredient', 'hierarchical'=>true));

2) Then I added some rewrite rules

add_rewrite_rule('^recipes-with-(.*)/page/([0-9]+)?$','index.php?ingredient=$matches[1]&paged=$matches[2]','top');
add_rewrite_rule('^recipes-with-(.*)/?','index.php?ingredient=$matches[1]','top');

3) The last thing I needed to do was adding a filter

add_filter( 'term_link', 'change_ingredients_permalinks', 10, 2 );

function change_ingredients_permalinks( $permalink, $term ) {
    if ($term->taxonomy == 'ingredient') $permalink = str_replace('ingredient/', 'recipes-with-', $permalink);
    return $permalink;
}

4) Flush rewrite rules (you only need to go to settings->permalink and click save)

2

I came up with this with the add_rewrite_rule():

add_rewrite_rule('^recipes-with-([^/]*)/?','index.php?ingredient=$matches[1]','top');

I did some testing for the above, and it works well when you use it for one taxonomy at time. Here is the code from my functions.php:

add_action( 'init', 'create_ingredient_tax' );
function create_ingredient_tax() {
    register_taxonomy( 
            'ingredient', 
            'post', 
             array( 'label' => 'Ingredient', 
            'hierarchical' => true
            ), 
            array( 'rewrite' => array (
                        'slug'=>'recipes-with'
                    ))
        );
}
// Remember to flush_rewrite_rules(); or visit WordPress permalink structure settings page
add_rewrite_rule('^recipes-with-([^/]*)/?','index.php?ingredient=$matches[1]','top');

I then used taxonomy-post_format.php template fiel from WordPress twentyfourteen theme to test that this works. I also flushed rewrite rules for the new rule to become effective.

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.