admin管理员组

文章数量:1122846

How do I redirect this page URL, http://localhost/wordpress_rnd/?page_id=2, to the home URL, http://localhost/wordpress_rnd/, without using any plugins?

How do I redirect this page URL, http://localhost/wordpress_rnd/?page_id=2, to the home URL, http://localhost/wordpress_rnd/, without using any plugins?

Share Improve this question edited Mar 14, 2015 at 6:44 Gabriel 2,24810 gold badges22 silver badges24 bronze badges asked Mar 14, 2015 at 4:58 codercoder 3932 gold badges3 silver badges9 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 22

The correct way to do this is using the template_redirect hook by adding a function to your functions.php:

function redirect_to_home() {
  if(!is_admin() && is_page('2')) {
    wp_redirect(home_url());
    exit();
  }
}
add_action('template_redirect', 'redirect_to_home');
add_action( 'init', function() {
    if ( 0 === stripos( $_SERVER['REQUEST_URI'], '/page_id=2' ) ) {

       wp_redirect( home_url(), 301 );
       exit;

    }
}

Put this code in a mu-plugin or in your theme's functions.php file

Locate page.php (assuming you've created it already). After this line <?php get_header(); ?> add the following code:

<?php if(is_page('2')) {
    wp_redirect( home_url(), '302' ); 
} ?>

In the code above, is_page('2') is actually the ID of your page as you've specified in your example.

WP_REDIRECT is the function that you need to use for redirecting in wordpress. It can be used like :

wp_redirect( $location, $status );
exit;
//$location is required parameter. It is used to give the target url to which page will get redirected.
//$status is optional. It is used to set status code. Default is 302

You can use this function to redirect users from one page to other. It should be placed in either functions.php or the template file which is being used to display the current page. Now to use it in your situation, simple place the following code at the bottom of your functions.php file

$redirectFromPageID = 2;  //Redirect from Page having ID of 2
$redirectTo = home_url(); //Redirect to Home URL

if( is_page( $redirectFromPageID ) ){
    wp_redirect( $redirectTo  );
    exit;
}

本文标签: Redirect page URL to home URL without using a plugin