我有一個技術問題,我希望對此有更多的見解而不是解決方案。
我將自定義函數掛鉤到 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 );
因此,如果任何未登錄到我的帳戶的人轉到“ressource”自定義帖子類型頁面,他們會使用標準的 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())
在前端執行 a時,它返回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 );
你的 user_id 是 11 嗎?
你需要看到single.php
:
$template
是'single-ressource.php'
:對get_current_user_id()
是11
:錯了,你不希望 id 是11
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句