如何在WordPress中即时重定向URL

How to instant redirect url in wordpress?

本文关键字:重定向 URL WordPress      更新时间:2023-09-26

我想在wordpress中立即重定向URL。这是我的脚本代码。

JS代码

jQuery(document).ready(function() {
    var x=window.location.href;
    if(x=='http://example.com/') {
        window.location.href='http://example.com/home';
    }
});

当我输入 url example.com/时,我希望它可以立即重定向到 example.com/home 而不显示 example.com/页面。我想在我的网站上按回车键时看到 example.com/home 页面。

最好在 htaccess 文件中创建重定向,如下所示:

#Redirect a single page:
Redirect 301 /pagename.php http://www.domain.com/pagename.html

您可以使用 RedirectMatch 进行重定向

.htaccess 文件

RedirectMatch ^/$ /home/

Wordpress提供了一个简单易用的重定向功能。只需将其放在模板的最顶部:

<?php
wp_redirect( 'http://example.com/home' );
exit;
?>

https://codex.wordpress.org/Function_Reference/wp_redirect

使用

Wordpress 框架本身执行此操作的一种方法是使用 wp_redirect - https://codex.wordpress.org/Function_Reference/wp_redirect

因此,您可以挂钩到wordpress的wp操作(以确保已设置$post项并运行以下命令。它将检查这是否是在阅读设置中设置的网站的主页,如果是,则重定向。

这不是处理此问题的最佳方法,因为它确实加载了某些页面,但它可能是您在此处问题的快速临时解决方案。只需将其添加到您的函数.php文件

add_action('init','redirect_home');
function redirect_home(){
    if(is_front_page()||is_home()){
        wp_redirect(get_site_url().'/home');exit;
    }
}

使用以下命令编辑您的 htaccess 文件:

RewriteEngine On
RewriteRule ^$ /home [R=301,L]
RewriteCond %{REQUEST_URI} ^/?