【问题标题】:Wodpress Query Parameter (?p) Redirect if not numericWordpress 查询参数 (?p) 如果不是数字则重定向
【发布时间】:2021-10-19 06:50:48
【问题描述】:

在wordpress中使用以下内容来获取特定帖子的结果

site_url?p=12

但如果它不是数字怎么办。让我们尝试使用site_url?p=test 而不是转到 404 它显示空白页?尝试使用正则表达式重定向

^site_url?p=[0-9]

但它没有成功。由于这个 p 是 wordpress 中的保留关键字。

任何想法如何检查它的值,以便如果它不是数字,我可以创建条件?

【问题讨论】:

  • 您知道? 是正则表达式中的元字符,需要转义吗? \??
  • 我使用的是redirect plugin,它确实允许我在没有\的情况下添加?
  • 你确定吗? If you want to match a character that is part of the regular expression syntax then you must escape it. For example, if you want to match ? then you will need to put \? as ? on its own has a special meaning.

标签: php regex wordpress redirect wordpress-theming


【解决方案1】:

您可以挂钩template_redirect 操作挂钩以将用户重定向到特定页面,无需插件!

例如,如果?p 不是数字,则以下代码会将用户重定向到您的网站home_url

add_action('template_redirect', 'your_theme_custom_page_redirect');

function your_theme_custom_page_redirect()
{
    global $wp_query;

    if (isset($_GET['p']) && $_GET['p'] != preg_match("~[0-9]~", $_GET['p']) && !is_admin()) {
        $wp_query->set_404();
        status_header(404);
        wp_safe_redirect(home_url());
        exit;
    };
};

如果您想将用户重定向到 404 页面并且您已经创建了一个页面,那么根据您的 404 页面路径及其所在位置,您可以执行以下操作:

add_action('template_redirect', 'your_theme_custom_page_redirect');

function your_theme_custom_page_redirect()
{
    global $wp_query;

    if (isset($_GET['p']) && $_GET['p'] != preg_match("~[0-9]~", $_GET['p']) && !is_admin()) {
        $wp_query->set_404();
        status_header(404);
        get_template_part(404); // This could change depending on the actual path of your 404 page
        exit;
    };
};

代码转到您活动主题的functions.php 文件。

【讨论】:

  • 但是我使用/^[0-9]*$/ 仅验证数字
  • 是的,那也行。这完全取决于您要如何设置。
猜你喜欢
  • 2012-05-28
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
相关资源
最近更新 更多