Pete Norris
Pete Norris

Reputation: 1054

Twig (Timber) + Wordpress - showing categories of a post

I am imagining suport for Timber is pretty thin, but perhaps my issue may be more twig related, or even just best php practices?

I am using ACF to list a group of posts on a page. As well as the usual details (title, content etc...) I want to display the categories that are assigned to the posts.

TIMBER CONTROLLER (jobs.php)

$context = Timber::get_context();
$post = new TimberPost();
$context['post'] = $post;
$context['categories'] = Timber::get_terms('category', array('parent' => 0));

$args = array(
'numberposts' => -1,
'post_type' => 'jobs'
);

$context['job'] = Timber::get_posts($args);

Timber::render( 'page-templates/job.twig', $context );

TWIG FILE

  <section id="job-feed">
    <h3> term.name }}</h3>
    {% for post in job %}
      <div class="job mix">
        <h2>{{ post.title }}</h2> 
        <p>{{ post.content }}</p> 

        <p>{{ function('the_category', '') }}

      </div>
    {% endfor %}    
  </section>

You will see I've tried reverting to using a WP function as I cannot find a way to do this in Timber, or any other way.

Upvotes: 3

Views: 21396

Answers (1)

Jared
Jared

Reputation: 1734

I assume you want the categories assigned to the particular job? In that case...

<section id="job-feed">
    {% for post in job %}
      <div class="job mix">
        <h2>{{ post.title }}</h2> 
        <p>{{ post.content }}</p> 

        <p>{{ post.terms('category') | join(', ') }}

      </div>
    {% endfor %}    
  </section>

What's going on?

With {{ post.terms('category') }} you're getting all the terms from the category taxonomy (attached to the post) returned to you as an array. Then Twig's join filter:

http://twig.sensiolabs.org/doc/filters/join.html

... will convert those to a string with commas. The result should be:

<p>Technical, On-Site, Design, Leadership</p>

Upvotes: 18

Related Questions