在木材枝杈文件里面的圈

时间:2018-03-08 19:22:03

标签: php wordpress timber

我有一个名为products的自定义帖子类型和名为type的自定义分类。

我需要显示每个类型的列表和三个帖子。喜欢这个


{鸡肉描述} |来自鸡类产品的三个帖子
猪肉
{猪肉描述} |来自猪肉类产品的三个帖子

对于类似的6种产品类型。

所以我在wordpress .php文件中有这个

$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as $term) {
    $args = array(
        'post_type'   => 'producto',
        'tax_query' => array(
            array(
                'taxonomy' => 'tipo',
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    );

    $context['product_'.$term->slug] = Timber::get_posts($args);
}

$context['cats'] = Timber::get_terms('tipo', array('orderby' => 'id'));

哪个应该给我product_pork和product_chicken以及其他所有

.twig文件中我有这个

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
{% endfor %}

在此之前一切都很好但是当我尝试这样做时

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in cat.slug %}
         {{product.title}}
    {% endfor %}
{% endfor %}

如果我试试这个,我什么都没得到

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in product_pork %}
         {{product.title}}
    {% endfor %}
{% endfor %}

当然它有效,我的问题是,有没有办法让它发挥作用?或者你认为另一种完全不同的方式?我愿意接受建议

非常感谢

1 个答案:

答案 0 :(得分:1)

问题出在这一行......

{% for product in cat.slug %}

cat.slug是一个字符串,因此没有办法迭代它。试试这段代码......

$terms = get_terms('tipo', array('orderby' => 'id'));
foreach ($terms as &$term) {
    $args = array(
        'post_type'   => 'producto',
        'tax_query' => array(
            array(
                'taxonomy' => 'tipo',
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    );

    $term->products = Timber::get_posts($args);
}

$context['cats'] = $terms;

嫩枝...

{% for cat in cats %}
    {{cat.title}}
    {{cat.description}}
    {% for product in cat.products %}
         {{product.title}}
    {% endfor %}
{% endfor %}