Wordpress 查询参数 (?p) 如果不是数字则重定向

Wodpress Query Parameter (?p) Redirect if not numeric

下面在wordpress中使用得到特定post

的结果
site_url?p=12

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

^site_url?p=[0-9]

但是没有成功。因为这个 p 是 wordpress 中的保留关键字。

知道如何检查它的值,以便在它不是数字时可以设置条件吗?

您可以挂接到 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 文件。