[英]Password protected page functionality not working out of the box with Timber/Twig (Wordpress)
我正在使用WordPress和Timber來構建自定義主題。 我需要網站頁面進行密碼保護。 我已經在此頁面的WordPress管理區域中更改了設置,但是現成的WordPress功能似乎不適用於Timber。 我四處搜索,發現以下代碼片段,但是它們不起作用。 我在這里做錯了什么?
在我的page.php
邏輯中:
$context = Timber::get_context();
$post = new TimberPost();
$context['page'] = $post;
$context['global'] = get_fields('options');
$context['protected'] = post_password_required($post->ID); // here i am trying to check if the current page is password protected and adding the check to the context
$context['password_form'] = get_the_password_form(); // grabbing the function to display the password form and adding it to the context
Timber::render( array(
'pages/page-' . $post->post_name . '.twig',
'pages/page.twig'
), $context );
在我的Twig模板中,我嘗試過:
{% if protected %}
{{ password_form }}
{% else %}
<!-- rest of page template here -->
{% endif %}
if
檢查似乎不起作用,它始終表示該頁面不受密碼保護,即使在WP管理員中另外指定了該頁面也是如此。 {{ password_form }}
確實正確顯示了密碼形式。
我也在page.php
嘗試了這個:
$context = Timber::get_context();
$post = new TimberPost();
$context['page'] = $post;
$context['global'] = get_fields('options');
if ( post_password_required($post->ID) ) {
Timber::render('page-password.twig', $context);
} else {
Timber::render(array('pages/page-' . $post->post_name . '.twig', 'pages/page.twig' ), $context);
}
使用page-password.twig
顯示密碼形式。 如果檢查也沒有用。
您可以使用以下代碼包含應使用密碼保護的內容:
if ( ! post_password_required() ) {
// Include password protected content here
}
您的page.php
看起來不錯。 那部分應該工作。 但是對於您的Twig模板,您需要更改if-else-tags的語法。 您將要使用Control Structure標記,因此需要使用{% %}
而不是回顯標記{{ }}
。
{% if protected %}
{{ password_form }}
{% else %}
{# Rest of the template here #}
{% endif %}
同時,這是作為Timber問題討論的,建議的添加密碼保護的新方法是使用過濾器: https : //timber.github.io/docs/guides/wp-integration/#using-a-filter 。
默認情況下,木材輸出用於輸入密碼的表格。
{{page.content}}
但是,如果您想知道頁面上是否有密碼,可以這樣做
$context = Timber::get_context();
$post = Timber::query_post();
$context['post'] = $post;
if ( post_password_required( $post->ID ) ) {
Timber::render( 'single-password.twig', $context );
} else {
Timber::render( array( 'single-' . $post->ID . '.twig', 'single-' . $post->post_type . '.twig', 'single.twig' ), $context );
}
另外,請嘗試在私人窗口上查看該頁面,因為如果您以admin身份登錄,則會看到一個正常頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.