如何在Timber索引页面中提供WordPress自定义功能?

时间:2017-05-22 20:59:53

标签: wordpress wordpress-theming timber

我正在尝试将我的标准PHP WordPress主题转换为Timber / Twig,并且无法从自定义函数获取任何输出。这个特别关注该帖子是否有一个Yoast主要术语集,它允许您为具有多个类别的帖子指定主要类别。

我需要在The Loop中执行此操作,大多数文档都会讨论如何在单个页面中执行此操作。我在functions.php中有这样的函数:

function my_theme_get_post_category() {
    // regular list of categories set in WP
    list( $wp_category ) = get_the_category();
    // primary category set with Yoast plugin
    $primary_category = new WPSEO_Primary_Term( 'category', get_the_ID() );
    $primary_category = $primary_category->get_primary_term();
    $primary_category = get_category( $primary_category );
    // use only one or the other
    if ( is_wp_error( $primary_category ) || $primary_category == null ) {
        $category = $wp_category;
    } else {
        $category = $primary_category;
    }
    return $category;
}

根据我在此处的“功能”部分(https://github.com/timber/timber/wiki/WP-Integration#functions)中所阅读的内容,我应该能够在{{ function('my_theme_get_post_category', post.ID) }}的模板中调用此功能,但这不起作用。

我尝试将$postID作为函数的必需参数,但这也没有任何帮助。

我还尝试使用TimberHelper::function_wrapper,然后使用{{ my_theme_get_post_category }}在模板中调用它,但是,再次,它没有完成任何任务。

1 个答案:

答案 0 :(得分:0)

如果您使用{{ function('my_theme_get_post_category', post.ID) }},则您调用的函数需要接受您传递的参数。当你使用...时

function my_theme_get_post_category() {
    // Your function code
}

...那么您的帖子ID将不会传递给该功能。如您所述,您可能已尝试将帖子ID添加为参数:

function my_theme_get_post_category( $post_id ) {
    // Your function code
}

没有任何事情发生。那是因为你的函数使用了依赖于The Loop的函数,比如get_the_category()get_the_ID()。这些函数从全局变量中获取当前的帖子ID ,这些变量在您遍历Timber中的帖子时并不总是设置。

使用Timber时,您需要告诉这些函数使用某个帖子ID。如果您查看get_the_category()的文档,您会看到有一个可以传递的可选参数:post id。

对于其他函数get_the_ID(),您只需将其替换为传递给函数的参数$post_id即可。

function my_theme_get_post_category( $post_id ) {
    // regular list of categories set in WP
    list( $wp_category ) = get_the_category( $post_id );

    // primary category set with Yoast plugin
    $primary_category = new WPSEO_Primary_Term( 'category', $post_id );
    $primary_category = $primary_category->get_primary_term();
    $primary_category = get_category( $primary_category );

    // use only one or the other
    if ( is_wp_error( $primary_category ) || $primary_category == null ) {
        $category = $wp_category;
    } else {
        $category = $primary_category;
    }

    return $category;
}