【问题标题】:Redirect WordPress 404 page to a specific page将 WordPress 404 页面重定向到特定页面
【发布时间】:2020-12-17 10:02:06
【问题描述】:

我在 WordPress 中构建了一个 404 页面,但我不知道如何将其设为 404 页面。在这里使用免费主题并且有一个 404.php 文件,但是我需要在那里写什么才能显示这个特定页面?

因此,如果有人编写 test.com/djashkdajhjkda,它会转到 test.com/404 并显示该页面的模板和内容。

我知道有插件可以解决这个问题,但我有点固执,希望有办法通过代码解决这个问题。 如果通过代码解决太复杂,我很乐意接受插件推荐。

【问题讨论】:

  • 如果你得到了你想要的答案,别忘了给对你有帮助的答案投票! :)

标签: wordpress


【解决方案1】:

将此代码放在您的 404.php 文件顶部。

<?php
// Here the WordPress will redirect to the page you want with a 301 status code.
// Remember to change the /path-to-go with the URL you like to redirect the users.
// 301 is permanent redirect. 302 is Temporary redirect.
wp_redirect(esc_url(home_url('/path-to-go')), 301);
// And here will stop the file execution.
exit();
?>

实现相同结果的另一种方法是将以下代码放入您的functions.php


add_action('template_redirect', 'redirect_if_404');
function redirect_if_404() {
    if ( is_404() ) {
        // Remember to change the /path-to-go with the URL you like to redirect the users.
        // 301 is permanent redirect. 302 is Temporary redirect.
        wp_redirect(esc_url(home_url('/path-to-go')), 301);
        // And here will stop the file execution.
        exit();
    }
}

通常谨慎应用此方法,因为它可能会损坏您网站的部分 SEO。

【讨论】:

  • 它不起作用:/ 只显示这样的空白页。而且我不需要担心 SEO,因为它是一个私人页面
  • 你把/path-to-go换成你想要的路径了吗?
  • @casualminna 如果您仍然得到白页,那么可以肯定的是,您的网站有其他问题。我向您展示的过程是保证如果您的安装当然也可以正常工作。
  • 是的,我做到了,但它不起作用。任何东西都没有损坏,因为这是我第一次在主题编辑器中触摸。会不会和我在本地运营有关?
  • 不幸的是,我无法判断我是否掌握了代码。但是我作为解决方案发送给您的 100%,它肯定有效。如果您仍然有白页,那么您的安装应该有其他问题。
猜你喜欢
  • 1970-01-01
  • 2018-02-07
  • 2019-01-15
  • 2011-10-06
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
相关资源
最近更新 更多