add rules for categories:
add_action( 'init', 'nz_add_category_rules' );
function nz_add_category_rules() {
$categories = get_categories( 'post' );
$cat_slug = array();
foreach ( $categories as $cat ) {
$cat_slug[] = $cat->slug;
}
$cat_regex = '(' . join( '|', $cat_slug ) . ')';
$regex = $cat_regex . '/([^/]+)$';
$redirect = 'index.php?category_name=$matches[1]&name=$matches[2]';
add_rewrite_rule( $regex, $redirect, 'top' );
}
add the filter for the post link: (the first category will be used)
add_filter( 'post_link', 'nz_get_permalink' );
function nz_get_permalink( $permalink ) {
global $post;
if ( $post->post_type == 'post' ) {
$category = get_the_category();
if ( isset( $category[ 0 ] ) ) {
$cat_slug = $category[ 0 ]->slug;
$permalink = trailingslashit( get_home_url() ) . trailingslashit( $cat_slug ) . $post->post_name;
}
}
return $permalink;
}
redirect to new url: (it is only necessary if you want to permanently redirect since the predefined permalink is still valid)
add_action( 'template_redirect', 'nz_redirect_posts', 100 );
function nz_redirect_posts() {
global $wp_query;
if ( $wp_query->get( 'name' ) && is_singular( 'post' ) && !$wp_query->get( 'category_name' ) ) {
$permalink = get_permalink( $wp_query->post );
wp_redirect( $permalink, 301 );
exit;
}
}