【发布时间】:2022-01-10 10:33:21
【问题描述】:
我正在使用Timber 将旧主题迁移到基于类的新设置。有一种称为“收藏”的自定义帖子类型。在一个循环中,我在概览页面上输出所有集合。每个计数表示该特定集合中有多少帖子。每个集合的标题用于获取具有相同名称的相关术语,然后我统计具有相应标签的帖子的数量。像这样:
$term_slug = get_the_title($post->ID, 'title');
$term = get_term_by('name', $term_slug, 'post_tag');
echo $term->count
这非常适合旧的基于 PHP 的模板。现在在新的 Timber 设置中,我尝试在我的 Twig 模板中直接调用 get_term_by 函数,如下所示:
{{function('get_term_by', 'name', post.title, 'post_tag', post.id)}}
但这会以错误 500 破坏整个网站。
我也尝试过使用 Timbers 的内置函数,例如 terms
post.terms( {query:{taxonomy:'post_tag'}}
{{function('get_term', 'post_tag')}}
两者都没有输出。然后我尝试将其添加为自定义函数,如it's suggested in this answer.。我有一个 Theme.php 文件,它负责所有的处理和加载:
// Theme.php
<?php
namespace Mytheme\Theme;
use Timber\Timber;
class Theme {
public function __construct() {
$this->theme = wp_get_theme();
Timber::$dirname = array( 'templates', 'source/views' );
}
public function run() {
// all the other loading stuff and then...
if(class_exists('Timber')) {
add_filter( 'timber/twig', function( \Twig_Environment $twig ) {
$twig->addFunction( new \Timber\Twig_Function( 'myFunction', 'myFunction' ) );
});
}
}
public function myFunction($term_slug, $taxonomy) {
$term = get_term_by('name', $term_slug, $taxonomy);
return $term->count;
}
}
在我的functions.php 中,我正在实例化并像这样运行它:
<?php
require_once( __DIR__ . '/vendor/autoload.php' );
$timber = new Timber\Timber();
// autoload stuff Packages and then...
if (!function_exists('sbx_theme')) {
function sbx_theme()
{
return Swissbeatbox\Theme\Theme::getInstance();
}
}
sbx_theme();
sbx_theme()->run();
此设置运行顺利,但添加 myFunction 后立即失败并出现错误:
Call to a member function addFunction() on null in ...timber/timber/lib/FunctionWrapper.php on line 75
所以甚至在我尝试在 Twig 中调用它之前。它失败。另外,如果我把它放在__constructfunction 中,同样的错误仍然存在。
我的目标是使用内置的 Timber 函数或调用自定义函数,例如:
{ {myFunction(post.title, 'post_tag', post.id) }}
或
{{ function('myFunction', post.title, 'post_tag', post.id) }}
【问题讨论】:
-
Both just output nothing- 我的意思是你知道{# ..... #}意味着代码被正确注释而不执行? -
糟糕我的错。只是复制和粘贴问题。当然,我试图在没有评论的情况下做到这一点。我刚刚编辑了答案。
标签: wordpress twig wordpress-theming timber