简体   繁体   中英

How do I redirect my WordPress site homepage to a landing page, while allowing the rest of the site to remain unaffected?

Here is the simple code I have placed before the on the Wordpress site:

<script type="text/javascript"> <!-- if (screen.width <= 800) {
window.location = "http://m.domain.com"; } //--> </script>

This issue is, this redirects all pages of our site to to the landing page. I only want the home page to be redirected. How would I write this?

Put this code in header.php of your theme.

    <?php
    if (is_front_page()) {
    echo '<script type="text/javascript"> <!-- if (screen.width <= 800) {
    window.location = "http://m.domain.com"; } //--> </script>';
    }
    ?>

Redirects with javascript can cause your website to be penalized by Google.

You are much better off using a Header redirect with PHP. You can detect mobile users based on their user agent rather that relying solely on the width of the browser window.

If you can't write all the code yourself, this plug-in could be helpful for that.

https://wordpress.org/plugins/equivalent-mobile-redirect/

Put this code right at the top of your themes header.php

<?php
    if(is_front_page())
        header('Location: http://example.com');

?>

This will only redirect on the front page. Just replace example.com with your desired url.

To setup a redirect for a different but specific page, you can use get_the_ID().

eg

<?php
    if(is_front_page())
        header('Location: http://example.com');
    elseif(get_the_ID() == PAGE ID HERE)
        header('Location: http://example2.com');
    elseif(get_the_ID() == PAGE ID HERE)
        header('Location: http://example3.com');
?>

if you want to redirect on all pages but still have homepage go somewhere else and leave some pages alone, use the below code.

<?php
    if(is_front_page())
        header('Location: http://example.com');
    elseif(get_the_ID() != PAGE ID HERE || get_the_ID() != 2ND PAGE ID HERE)
        header('Location: http://example2.com');
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM