我正在使用Timber + WooCommerce并尝试在首页上显示产品的自定义查询,但是循环缺少价格,但显示了图像和标题。但是,归档页面和单个产品页面会显示价格。
查询应该在woocommerce.php页面上吗?我在这里想念什么?
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);
page-home.twig
{% for post in top_selling %}
{% include 'woocommerce/tease-product.twig' %}
{% endfor %}
tease-product.php
<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>
// This part here shows the price on archive and single-product pages' only. It needs to show the price on front page, too.
{% do action( 'woocommerce_after_shop_loop_item_title' ) %}
</div>
woocommerce.php
<?php
if ( ! class_exists( 'Timber' ) ) {
echo 'Timber not activated. Make sure you activate the plugin in <a href="/wp-admin/plugins.php#timber">/wp-admin/plugins.php</a>';
return;
}
$context = Timber::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 = Timber::get_posts();
$context['products'] = $posts;
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 );
}
答案 0 :(得分:0)
除非设置了global $product
,否则价格不会以您调用的方式显示。
嫩枝模板{{ fn('timber_set_product', post) }}
中的函数调用应解决这一问题,但是,如果您从woocommerce and wood教程中复制并粘贴了该函数,则需要对其进行编辑。
原始功能
<?php
function timber_set_product( $post ) {
global $product;
if ( is_woocommerce() ) {
$product = wc_get_product( $post->ID );
}
}
新功能
<?php
function timber_set_product( $post ) {
global $product;
// is_woocommerce() does not return true on the front_page by default!
if ( is_woocommerce() or is_front_page() ) {
$product = wc_get_product( $post->ID );
}
}
您甚至可以完全取消is_woocommerce()
检查,然后由您决定确保仅在适当的时间调用它。