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