Bryce
Bryce

Reputation: 367

Search all posts by an author in Wordpress/Timber

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?

Upvotes: 0

Views: 640

Answers (2)

Phil Veloso
Phil Veloso

Reputation: 1136

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 ) }}

Upvotes: 2

Ihar Aliakseyenka
Ihar Aliakseyenka

Reputation: 14333

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 %}

Upvotes: 1

Related Questions