菜单 links 上的木材散列 link 过滤器

Timber hash link filter on menu links

我正在用 Timber 在 WordPress 中构建一个单页主题,但我对它有点陌生,所以我对一些可能非常简单的东西有点迷茫。我只想使用过滤器将链接转换为散列链接,但我什至无法将过滤器正确无误地设置为 运行(当我像下面这样添加它时,我只是得到一个损坏的站点)。这是我的 functions.php 在我的主题(概要)中的样子:

 class SIDSite extends TimberSite {

        function __construct() {
            add_theme_support( 'post-formats' );
            add_theme_support( 'post-thumbnails' );
            add_theme_support( 'menus' );
            add_filter( 'timber_context', array( $this, 'add_to_context' ) );
            add_filter( 'get_twig', array( $this, 'add_to_twig' ) );
            add_action( 'init', array( $this, 'register_post_types' ) );
            add_action( 'init', array( $this, 'register_taxonomies' ) );
            add_filter( 'hash_link', array( $this, 'hash_link' ) ); // Added this
            parent::__construct();
        }

        function hash_link ($string) { // function I added, is probably not 100% right but I can't even debug it
            if(substr($string, 0, 1) === '/') {
                $string = substr($string, 1);
            }

            return '#' . $string;
        }
}

这是我的 menu.twig 文件:

{% if menu %}
    <ul>
    {% for item in menu %}
        <li class="{{item.classes | join(' ')}}">
            <a href="{{item.path | hash_link}}">{{item.title}}</a>
            {% include "menu.twig" with {'menu': item.get_children} %}
        </li>
    {% endfor %}
    </ul>
{% endif %}

我觉得我需要扩展其他东西,但将我的过滤器添加到整个站点应该在我看来可行。我该怎么做才能阻止我的网站崩溃?

你很接近,问题是 Twig 过滤器与 WP 过滤器完全分开,所以你需要在 Twig 而不是 WordPress 上注册你的过滤器。试试这个...

function add_to_twig( $twig ) {
    $twig->addFilter('hash_link', array( $this, 'hash_link' ));
    return $twig;
}

function hash_link( $string ) { /
    if(substr($string, 0, 1) === '/') {
        $string = substr($string, 1);
    }
    return '#' . $string;
}