如何将帖子 ID 传递给像 edit_post_link 这样的 Twig/Timber 函数?
在 https://timber.github.io/docs/guides/functions/#function-with-arguments 阅读文档
A function like edit_post_link will try to guess the ID of the post you want to edit from the current post in The Loop. the same function requires some modification in a file like archive.twig or index.twig. There, you will need to explicitly pass the post ID.
这就是发生的事情;当我使用它时
{{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', post.ID) }}
在index.twig
,所有编辑链接都具有显示自定义帖子类型循环的页面的帖子 ID,而不是循环中每个自定义帖子类型的帖子 ID。
我在 functions.php 中使用下面的函数,它也会强制执行 target="_blank"
在编辑链接上:
add_filter( 'edit_post_link', 'newwindow_edit_post_link', 10, 3 );
global $post;
$post_id = $post->ID;
function newwindow_edit_post_link( $link, $post_id, $text ) {
if( !is_admin() )
$link = str_replace( '<a ', '<a target="_blank" ', $link );
return $link;
}
这是 index.twig
上的基本循环. “people”是标准的 WordPress 自定义帖子类型:
{% if people %}
{% for person in people %}
<a href="{{ person.link }}">{{ person.name }}</a>
{{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', post.ID) }}
{% endfor %}
{% else %}
{% endif %}
这导致所有编辑链接都指向该页面,而不是每个自定义帖子类型“人”。
那么如何调用帖子ID呢?我是否需要在自定义帖子类型函数中调用帖子 ID?
主 index.php 文件具有标准的 Twig 函数:
$context = Timber::get_context();
$context['posts'] = Timber::get_posts();
$templates = array( 'index.twig' );
Timber::render( $templates, $context );
最佳答案
So how do I call the post ID?
如果 index.twig
模板循环中的 people
是一个帖子数组(即每个帖子都是一个 WP_Post
/Timber\Post
实例),然后您可以(或应该)通过 person.ID
或 person.id
(是的,两者 实际上都是 set )。所以这些对我来说效果很好:
{{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', person.id) }}
{{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', person.ID) }}
我是如何确认以上内容的
我安装并激活了 official Timber starter theme .
我创建了
front-page.php
:<?php $context = Timber::get_context(); // Here, I defined the `people`. $context['people'] = Timber::get_posts( [ 'post_type' => 'post', // yours would be 'person' and not 'post' 'posts_per_page' => 3, ] ); // This I used for testing only. $context['post'] = new Timber\Post(); $templates = array( 'front-page.twig' ); Timber::render( $templates, $context );
然后我创建了
templates/front-page.twig
:{% extends "base.twig" %} {% block content %} <h2>The queried page's title: {{ post.title }}</h2> <p>The queried page's ID: <b>{{ post.id }}</b></p> {% if people %} {% for person in people %} <a href="{{ person.link }}">{{ person.name }}</a> {{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', person.id) }}<br> {% endfor %} {% else %} {% endif %} {% include 'partial/pagination.twig' with { pagination: posts.pagination({show_all: false, mid_size: 3, end_size: 2}) } %} {% endblock %}
一切对我来说都很好——edit_post_link()
被正确调用并在标记中显示带有 target="_blank"
的帖子链接。 (我把 newwindow_edit_post_link
的东西放在 functions.php
中)
关于php - 将帖子 ID 传递给 Twig/Timber 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974561/