Redirecting permalinks

1

I have a website developed in Wordpress, and the main structure is: www.teste.com.br/titulo-do-post only, I will have to modify it to: www.teste.com.br/categoria-do-post/titulo-do-post

All the links I shared as shown in the first form will no longer work, not counting the relevance of Google. What should I do?

I'm changing here:

    
asked by anonymous 15.10.2014 / 14:49

2 answers

2

The plugin Redirection serves to manage 301 redirects, which is what you need.

Another way to solve the problem, but that requires more knowledge, is to create Rewrite Rules directly in the configuration of your site in Apache, through the file .htaccess

    
15.10.2014 / 16:22
1

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

}
    
15.10.2014 / 16:37