javascript - 如何在 WordPress 中为不存在的子页面显示 404 页面?

标签 javascript php html css wordpress

我们的网站是用 WordPress 构建的,我注意到我们的网站不会重定向不存在的子页面路由。

例如,我有一个名为 about-us 的页面,该页面的完整 url 为 http://example.com/about-us 那么如果我转到about-us 的一个不存在的子页面路由 http://example.com/about-us/1/ 它正在显示其父 的内容code>/about-us

/about-us/1/ 应该重定向到 WordPress 的 404 页面,因为它不存在。

我在 functions.php 中尝试了下面的代码,但它只会停止自动猜测 url

remove_filter('template_redirect', 'redirect_canonical');

非常感谢任何帮助。谢谢

最佳答案

当您在 URL 末尾添加 /(number)/ 时,例如在您的情况下 /1/,WordPress 默认将其解析为页面参数.这对存档页面很有用,但对单个帖子和页面没有用。

您可以通过将此代码添加到 functions.php 文件来自行检查。

  function show_wp_query() {
    global $wp_query;

    echo "<pre>";
    die(var_dump($wp_query)); 
    echo "</pre>";
  }

  add_action('wp', 'show_wp_query');

  -------------------------
  Top section of the output
  -------------------------

  ["query"]=>
  array(2) {
    ["page"]=>
    string(1) "1"
    ["name"]=>
    string(8) "about-us"
  }

但是,当您尝试访问任意子页面时,您会看到 WordPress 实际上正在加载 404 页面。试试这个 URL - http://example.com/about-us/sub-page


不太好的解决方案:但是,如果您绝对需要实现此行为,我可以建议您使用我称之为不太好的解决方案。

  function load_404_page_for_paged_urls() {
    global $wp_query;
    if( !is_single() && !is_page() ) return;

    $page = get_query_var( 'page' );

    if( $page  > 0 ) {
      $wp_query->set_404();
      status_header( 404 );
      get_template_part( 404 );
      exit(); 
    }

  }

  add_action('wp', 'load_404_page_for_paged_urls');

希望这对你有用。谢谢。

关于javascript - 如何在 WordPress 中为不存在的子页面显示 404 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57388418/

相关文章:

php - 对 mysql_fetch_array 内的数组进行排序

php - 架构生成器 : Create Table if not exists

javascript - 使用maphilight jquery插件同时保持两种颜色

jquery - Angular 日期范围选择器中的奇怪行为

javascript - 将单个对象解构为多个对象的数组

function-pointers - 在 javascript 中,定义内联函数与将其作为引用传递有何权衡?

javascript - Express JS : Can I still have &lt;scripts> in my index. html

php - 替换 URI 查询字符串中的值

css - 获取 DIV 标签以扩展到页面或内容的底部

javascript - Mechanize 和Javascript