0

我正在尝试将我的标准 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 }}但同样没有完成任何事情。

4

1 回答 1

0

如果您使用{{ function('my_theme_get_post_category', post.ID) }},那么您调用的函数需要接受您传递的参数。当你使用...</p>

function my_theme_get_post_category() {
    // Your function code
}

...那么您的帖子 ID 将不会传递给该函数。正如您所提到的,您可能已经尝试将帖子 ID 作为参数添加:

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

什么也没发生。那是因为你的函数使用了依赖于循环的函数,比如get_the_category()or get_the_ID()。这些函数从全局变量中获取当前的帖子 id,当您在 Timber 中循环浏览帖子时并不总是设置这些变量。

使用 Timber 时,需要告诉这些函数使用某个 post 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;
}
于 2017-05-23T13:45:06.603 回答