首页 > 解决方案 > 是否可以链接到 Timber 模板中的其他静态页面?

问题描述

目前,要链接到“常见问题”页面,我有以下内容:

Check out our <a href="{{ site.link }}/faq">FAQ</a> page.

但是,我希望能够链接到我的 WordPress 主题中的其他内部页面,而无需在其后手动写入 URL 参数。就像是:

Check out our <a href="{{ site.link('faq') }}">FAQ</a> page.

这在木材中是不可能的吗?我已经检查了文档,但没有看到任何对它的引用,但我觉得我一定遗漏了一些东西。

标签: phpwordpresstwigwordpress-themingtimber

解决方案


Wordpress 有两个函数可以解决它:get_page_by_path()get_permalink()

get_page_by_path('page-slug');
get_permalink(page_id);

使用 Timber,您可以编写类似这样的调用 Timber 函数

{{ function('get_permalink', function('get_page_by_path', 'page-slug')) }}

但可以肯定的是,您应该定义一个 wp 函数以使其不疯狂。您可以使用 functions.php 文件向 WordPress 添加功能,即使您应该定义一个类来扩展 Timber(如果没有,请复制并粘贴它)

class StarterSite extends Timber\Site {
    public function __construct() {
        add_filter( 'timber/twig', array( $this, 'add_to_twig' ) );
        add_filter( 'timber/context', array( $this, 'add_to_context' ) );
        $this->add_routes();
        parent::__construct();
    }
    
    public function add_to_context( $context ) {
        $context['menu']  = new Timber\Menu();
        $context['site']  = $this;      
        return $context;
    }

    public function add_to_twig( $twig ) {
        $twig->addFunction( new Timber\Twig_Function( 'get_permalink_by_slug', function($slug) {
            return get_permalink( get_page_by_path($slug) );
        } ) );
        return $twig;
    }

}
new StarterSite();

如您所见,我定义了一个名为 get_page_by_slug 的 Twig 函数,它接收带有页面 slug 的字符串。现在,您可以将其写在您的模板上:

{{ get_permalink_by_slug('page-slug') }}

享受 :)


推荐阅读