A page can be redirected to a new page or URL. There are different methods to achieve this. In this blog post we will deal with all these methods in details.
Use of these methods depends upon different use cases. Sometimes HTML redirect work perfectly, in some cases JavaScript or PHP.
There is a WordPress function which can also be used and I think it is best to use WordPress function.
Here are different methods for redirect
HTML Method
In this method we will use meta redirect. Add following code in head section(between <head> and </head>) of your theme header.php .
0
1
2
|
<meta http-equiv=“refresh” content=“1; url=http://example.com/” />
|
Where
http://exampe.com is the url where we want to redirect.
JavaScript Method
window.location object can be used to redirect current page URL to new URL using following code block. Write this block in head area(between <head> and </head>) of header.php
0
1
2
3
4
|
<script>
window.location.href = “http://example.com”
</script>
|
PHP Method
Add following code at top of header.php
0
1
2
3
4
5
6
7
|
<?php
header(“Location: http://example.com/”);
exit;
?>
|
WordPress Method
There is a function in WP which can be used to redirect purpose.
0
1
2
3
4
5
|
<?php
wp_redirect( ‘http://www.example.com’, 301 );
exit;
?>
|
Where 301 is HTTP Status Code.
These redirect codes can be wrapped in conditional tags(is_single(),is_home() etc) of WordPress for greater results.
Some use case example
Redirect a page with ID 23 to contact page using HTML method.
0
1
2
3
4
5
6
7
8
|
<?php
if( is_page(23) ) {
<meta http–equiv=“refresh” content=“1; url=http://example.com/contact” />
}
?>
|