首页 > 解决方案 > 受密码保护的页面功能无法使用 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显示密码表格。如果检查也不起作用。

标签: phpwordpresstwigpassword-protectiontimber

解决方案


您可以使用此代码包含应受密码保护的内容:

if ( ! post_password_required() ) {

    // Include password protected content here    

}

推荐阅读