0
<?php
$permalink = get_permalink( $id );  
header("Location: ".$permalink, true, 301);
?>

Iam redirecting the URL without the id to id with 301 this php code is giving me problems, is the correct way to do it.

1

Don't use php header function it will cause problems within wordpress.

Wordpress has its own function to make redirects

Function Reference: wp_redirect($url, $status_code);

Try this:

<?php
$permalink = get_permalink( $id );  
wp_redirect($permalink, 301);
exit;
?>

Updated:

I've worked out some code for you

Place this below code to your functions.php file:

function redirector($post_id) {
    if (is_single()) {
        $redirect_to = get_permalink($post_id);
        if (empty($_SERVER['HTTPS']))
            $ht_prot = 'http://';
        else
            $ht_prot = 'https://';

        $cur_link = $ht_prot . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        $pattern = '/'.$post_id.'\/+$/';
        preg_match($pattern, $cur_link, $matches);

        if(sizeof($matches) < 1) :
            wp_redirect($redirect_to, 301);
            exit;
        endif;
    }
}

And call this function to your single.php file:

redirector($post->ID);
get_header(); ?>

Just before the get_header();

It will only redirect if you're in single post.

You can further change this code as your needs.

Caution:

If later you wish to change the permalink structure please remove the function call because it will continuously redirect and cause an redirect error.

4
  • I currenly have a URL a: /%postname%/%post_id% but even if i remove post-id the page loads i want to make it a 301 redirect to /%postname%/%post_id% – Shabbir Lakdawala Sep 5 '13 at 8:06
  • when i set custom permalink structure /%postname%/%post_id%/ it gives 404. How actually its working for you and what do you mean by 'if i remove post-id the page loads' – Rahil Wazir Sep 5 '13 at 11:15
  • For Example the URL: url.com/article-name/post-id, when i remove post-id the page has the URL like this url.com/article-name. What i want if i remove post-id the URL should 301 redirect to this url.com/article-name/post-id and the page should not load without post-id in the URL – Shabbir Lakdawala Sep 5 '13 at 11:37
  • See my updated answer – Rahil Wazir Sep 5 '13 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.