add Rules to 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 to 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 redirect permanently since the preset 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;
}
}
as Voce is modifying the structure?
– tinos
I changed the question.
– Felipe Viero Goulart
You want to know how to implement the new structure or what you will go through with the predetermined one after implementing?
– tinos
I want to know how to keep the old links. And make a redirect to the new link.
– Felipe Viero Goulart