Redirect Duplicated URL in Wordpress Customized Permalinks

i want to ask you about something that i really confuse to solve. I have a problem with my wordpress site, it has duplicated URL with the same result.

  1. www.site.com/some-blog-post
  2. www.site.com/news/some-blog-post

I got the number 2, when i modified my themes functions :

add_action( 'init', 'add_news_slug_permalink', 1 );
function add_news_slug_permalink() {
    register_post_type( 'post', array(
        'rewrite' => array( 'slug' => 'news'    ),
    ) );
}

The question is, how to redirect or disabled URL without news slug to URL with news slug? Thanks.

Upvotes: 2

Views: 170

Answers (1)

I got the solution, in this case, i add an action in my function.php , it's like :

add_action('template_redirect', 'redirect_to_news_slug', 20);

function redirect_to_news_slug() {

    global $post;

    /**
     * Check if the page is single Post
     */
    if ($post->post_type == 'post' && (is_category() == false) &&
        (is_single() == true) && (is_home() == false)) {

        $currentUrl = $_SERVER["REQUEST_URI"];

        /**
         * Remove slash from URL, and get the first slug
         */
        $partOfUrl = array_filter(explode('/', $currentUrl));

        /**
         * Check if URL doesn't have 'news'
         */
        if ($partOfUrl[1] !== 'news') {

            /**
             * set new URL with 'news' slug
             */
            $newUrl = home_url().'/news/' . $partOfUrl[1];

            /**
             * Redirect to new URL
             */
            wp_redirect( $newUrl,301 );
            exit;
        }
    }
}

Upvotes: 1

Related Questions