【发布时间】: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