Jandon
Jandon

Reputation: 625

Get custom post type label instead of name - WordPress + Timber

I created 3 custom post types in WordPress : dissertation, subject-imposed, subject-free

In each custom post type the user is allowed to create only ONE post.

I created a menu composed with those three custom post types which allow to switch from post to another from the same user.

But I got a problem. The menu item display the name of the post type and not the label.

I got : DISSERTATION / SUBJECT-IMPOSED / SUBJECT FREE

And I would like the label (labels are in french) : MEMOIRE / SUJET IMPOSE / SUJET LIBRE

How can I get the label instead ? Thank you in advance.

In single.php :

$post_queried = get_queried_object();
$context['post_type_current'] = get_post_type_object(get_post_type($post_queried));

$get_post_current_user = get_posts( array(
    'author' => $current_user->ID,
    'post_type' => array('dissertation', 'subject-imposed', 'subject-free'),
));

$context['list_posts_current_user'] = $get_post_current_user;

In single.twig :

<ul class="menu-secondary__list">
    {% for item in list_posts_current_user %}
        {% set active = (post_type_current.name == item.post_type) ? 'active' : '' %}
        <li class="menu-secondary__item"><a href="{{ item.guid }}" class="menu-secondary__link h-item {{ active }}">{{ item.post_type }}</a></li>
    {% endfor %}
</ul>

Upvotes: 1

Views: 1366

Answers (1)

Jared
Jared

Reputation: 1734

Two steps to fix this one, first ...

Convert into an array of Timber\Posts

$get_post_current_user is an array of WP_Posts we need to convert these to Timber\Posts in order to interact with Timber's methods. Many ways to do this, but the easiest ...

{% for item in Post(list_posts_current_user) %}

Access the type method:

Now you can use the Post::type() method in your Twig template and access the labels:

{{ item.type.labels.name }}

The {{ item.type }} property will give you everything from here:

https://developer.wordpress.org/reference/functions/get_post_type_object/

Upvotes: 1

Related Questions