0

I'm trying to display all posts by a given author on the search results page using Timber. I've found that this works if I manually type it in:

/s?&author_name={username}

But I need to create these links dynamically in a loop, and unfortunately Timber's User object doesn't have access to a User's username. Going by ID also doesn't work (/s?&author={author_id}).

What's the solution here?

2 Answers 2

2

I would suggest you make a function available in Twig which allows you to pass in the author id and return the author archive link via get_author_posts_url() or access the WP user class.

See documentation on how to achieve this:

https://timber.github.io/docs/guides/functions/#make-functions-available-in-twig

php

add_filter( 'timber/twig', 'add_to_twig_author_link' );

function add_to_twig_author_link( $twig ) {
    $twig->addFunction( new Timber\Twig_Function( 'get_author_posts_url', 'get_author_posts_url' ) );
    return $twig;
};

twig

{{ get_author_posts_url( author_id ) }}
1

If you need to access author archive via link, you can do it by Timber\Post object

{% for post in posts %}
  <a href="{{ post.author.link }}">{{ post.author.name }}</a>
{% endfor %}

But as I understood, your problem is to pass user login into twig templates. This way you can add to a global context all of your users.

search.php

$ctx = Timber::context();
$ctx['users'] = get_users(); // it will return array of WP_User objects
Timber::render( 'search.twig', $ctx );

search.twig

{% for user in users %}
  {{ user.user_login }} // this will show user login
{% endfor %}
1
  • This isn't quite what I'm looking for, but it's still helpful, particularly having users (including their login) available in the the context. Thanks!
    – Bryce
    May 23, 2021 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.