木材和WooCommerce在循环中显示自定义类别

时间:2019-06-19 00:00:06

标签: php wordpress woocommerce timber

我正在使用Timber和WooCommerce。我有一个称为“品牌”的自定义分类法,其中为每种产品分配了一个品牌类别。该品牌必须显示在产品循环内的产品标题上方(tease-product.twig)。它必须显示在所有模板上,无论是首页,存档还是单个。

我目前拥有的内容适用于存档页面,但是我需要品牌类别才能显示在主页和单个产品页面上。

woocommerce.php

$context            = Timber::get_context();
$context['sidebar'] = Timber::get_widgets( 'shop-sidebar' );

if ( is_singular( 'product' ) ) {
    $context['post']    = Timber::get_post();
    $product            = wc_get_product( $context['post']->ID );
    $context['product'] = $product;

    // Get related products
    $related_limit               = wc_get_loop_prop( 'columns' );
    $related_ids                 = wc_get_related_products( $context['post']->id, $related_limit );
    $context['related_products'] =  Timber::get_posts( $related_ids );

    // Restore the context and loop back to the main query loop.
    wp_reset_postdata();

    Timber::render( 'views/woocommerce/single-product.twig', $context );
} else {
    $posts = $products = Timber::get_posts();
    $context['products'] = $posts;

    foreach($products as $product) {
        $product->brands = get_the_terms($product->ID, 'brands');

        if (empty($product->brands)) {
            $product->brands = new stdClass();
      }
    }

    if ( is_product_category() ) {
        $queried_object = get_queried_object();
        $term_id = $queried_object->term_id;
        $context['category'] = get_term( $term_id, 'product_cat' );
        $context['title'] = single_term_title( '', false );
    }

    Timber::render( 'views/woocommerce/archive.twig', $context );
}

tease-product.twig

<div class="column is-6 is-4-desktop is-3-widescreen has-text-centered">

    {{ fn('timber_set_product', post) }}

    <a href="{{ post.link }}">
        <img src="{{ post.thumbnail.src | resize(450) }}" alt="{{ post.title }}" />
    </a>

    {% if post.brands | length > 0 %}
        {% for brand in post.brands %}
            <div>{{ brand.name }}</div>
        {% endfor %}
    {% endif %}

    <a href="{{ post.link }}">
        <div>{{ post.title }}</div>
    </a>

    {% do action( 'woocommerce_after_shop_loop_item_title' ) %}
</div>

page.php(用于在首页显示产品)

$context = Timber::get_context();
$page = new TimberPost();
$context['post'] = $page;

if ( is_front_page() ) {
    $top_selling = [
        'post_type' => 'product',
        'posts_per_page' => 4,
        'post_status' => 'publish'
    ];
    $context['top_selling'] =  new Timber\PostQuery($top_selling);
}

Timber::render(array('page-' . $page->post_name . '.twig', 'page.twig'), $context);

感谢您的帮助。

0 个答案:

没有答案