How do I pass a post ID to a Twig/Timber function like edit_post_link?
Reading the docs at 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.
And that is what happens; when I use this
{{ function('edit_post_link', 'Edit', '<span class="edit-link">', '</span>', post.ID) }}
in index.twig
, all the edit links have the post ID of the page that displays the loop of custom post types, not the post ID of each custom post type that is in the loop.
I'm using the function below in functions.php, which also forces a target="_blank"
on edit links:
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;
}
This is the basic loop on index.twig
. "people" is a standard WordPress custom post type:
{% 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 %}
That results in all of the edit links pointing to that page, not each custom post type "person."
So how do I call the post ID? Do I need to call the post ID in the custom Post Type function?
The main index.php file has standard Twig functions:
$context = Timber::get_context();
$context['posts'] = Timber::get_posts();
$templates = array( 'index.twig' );
Timber::render( $templates, $context );