简体   繁体   中英

I can't find a way to loop through categories and the posts per categories with wordpress

i'm making a wordpress website with a theme that allowes me to use twig templates per page.

In functions.php i get the custom categories i want by doing

    $context['test'] = get_terms('workshop_category');

    foreach($context['test'] as $key => $value){
        $args = [
            'post_type' => 'workshop',
            'workshop_category' => $context['test'][$key]->id,
            'posts_per_page' => -1,
        ];

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


    }

Within that loop i want to loop all the workshops per workshop_category. With the current code and the twig code i get all the workshops underneath every category. But it only needs to be the ones that have that category

<li class="navigation__list__item hasMenu"><a href="#">Workshops</a>
                <div class="dropdown">
                    <ul class="dropdown__menu">
                        {% for workshop in test %}
                            <li class="dropdown__menu__item">
                                <a class="dropdown__menu__item__title" href="{{ workshop.link }}">{{ workshop.name }}</a>
                            </li>
                            {% for w in workshops %}
                                <li class="dropdown__menu__item">
                                    <a class="dropdown__menu__item__title" href="{{ w.link }}">{{ w.title }}</a>
                                </li>
                            {% endfor %}
                        {% endfor %}
                    </ul>
                </div>
            </li>

This is what i get returned: Category 1: workshop 1 workshop 2, Category 2: workshop 1 workshop 2. I

Assuming your workshop_category is a custom post meta you habe to use meta_query key in your $args like this:

$args = [
    'post_type' => 'workshop',
    'meta_query' => [
        ['key' => 'workshop_category', 'value' => $context['test'][$key]->id]
    ],
    'posts_per_page' => -1,
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM