skip to Main Content

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


  1. 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 TimberTwig_Function( 'get_author_posts_url', 'get_author_posts_url' ) );
        return $twig;
    };
    

    twig

    {{ get_author_posts_url( author_id ) }}
    
    Login or Signup to reply.
  2. If you need to access author archive via link, you can do it by TimberPost 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 %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search