【问题标题】:"get_current_user_id()" strict comparison with number fails“get_current_user_id()”与数字的严格比较失败
【发布时间】:2022-01-07 22:50:46
【问题描述】:

我有一个技术问题,我希望获得见解而不是解决方案。

我在 WordPress functions.php 中将一个自定义函数连接到“template_include”过滤器,如下所示,以便在页面上工作,而不会被其他人看到。

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() === 11 ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

因此,如果没有登录我的帐户的任何人转到“资源”自定义帖子类型页面,他们会看到标准的 single.php 布局而不是 single-ressource.php 布局。

问题是,它不能按原样工作。我必须将严格比较中的11 整数更改为'11' 字符串以使其工作查看编辑),如下所示。

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() === '11' ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

我去看了get_current_user_id() 函数的官方文档,似乎他们使用类型转换来返回整数或0

此外,当我在前端执行var_dump(get_current_user_id()) 时,它会返回int(11)

有人知道为什么第二个代码有效查看编辑)而不是第一个?

编辑

正如@Bazaim 指出的那样,我只是对所涉及的逻辑感到困惑。

使用第二个代码,我想隐藏的实际“single-ressource.php”并没有对任何人隐藏,因为传递的条件背后的逻辑存在缺陷。我只重定向user_id 等于字符串'11' 的用户,因为user_id 是整数。

下面的代码完美运行。

function template_redirect( $template ) {
    if ( $template === locate_template('single-ressource.php') && get_current_user_id() !== 11 ) { 
        return $new_template = locate_template( array( 'single.php' ) );
    }
    return $template;
};
add_filter( 'template_include', 'template_redirect', 99 );

【问题讨论】:

    标签: php wordpress comparison-operators


    【解决方案1】:

    你的 user_id 是 11 吗?

    您需要查看single.php

    • $template'single-ressource.php' :对
    • get_current_user_id()11 :错了,你希望 id 不是 11

    【讨论】:

    • 确实!谢谢你指点我,我一定很困惑。
    • 我看不到这一点,为什么 OP 的第二个示例有效呢?
    • 因为我基本上要求对使用等于字符串“11”的 user_id 登录的任何人隐藏正确的模板,因为 user_id 是整数,所以每个人都是如此。这意味着第二个示例实际上不起作用,因为每个人都可以看到带有我正在处理的模板的页面,而不是我想要重定向到的标准。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多