0

With my website I work with my own taxonomy. And I want that the taxonomy is intergrated with the permalink. So if an news page has a taxonomy, the permalink change.

Like this: mysite.com/%custom_tax%/blog/%postname% And if it's a page this: mysite.com/%custom_tax%/%postname%

But if there is no taxonomy I want: mysite.com/blog/%postname% And if it is an page: mysite.com/%postname%

How can I easily do this?

I already set up the %custom_tax% :

add_filter('post_link', 'custom_tax_permalink', 10, 3);
add_filter('post_type_link', 'custom_tax_permalink', 10, 3);


function custom_tax_permalink($permalink, $post_id, $leavename) {
    if (strpos($permalink, '%custom_tax%') === FALSE) return $permalink;

    // Get post
    $post = get_post($post_id);
    if (!$post) return $permalink;

    // Get taxonomy terms
    $terms = wp_get_object_terms($post->ID, 'custom_tax');  
    if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
    else $taxonomy_slug = '';


    flush_rewrite_rules();
    return str_replace('%custom_tax%', $taxonomy_slug, $permalink);
}
1
  • 1
    Don't call flush_rewrite_rules();. Especially not every time you retrieve a link. You should flush rewrite rules only once and when the rewrite rules are changed. Take that line out and instead visit the Permalinks > Settings page to flush the rules. Apr 10, 2012 at 15:20

1 Answer 1

1

Try something like this:

function custom_rewrite( $wp_rewrite ) {

    $feed_rules = array(
        '(.+)/blog/(.+)'      =>  'index.php?custom_tax='.$wp_rewrite->preg_index(1).'&post_name=' . $wp_rewrite->preg_index(2)
    );

    // ( array merge must be done this way, to ensure new rule comes first )
    $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' );

Remember to flush permalinks by visiting the permalinks page and re-saving if you add/change this code. Also remove the flush_rewrite_rules(); as advised by Stephen, it's unnecessary and bad practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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