我想在第三个产品之后展示一些内容(也许还有第六个,第九个……) 指产品类别。 不是每一个类别都有额外的内容或相同数量的内容。 所以它应该是灵活的。
我找到了一个使用以下代码的示例(https://stackoverflow.com/A/45580244/1788961):
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'template-parts/content' ); ?>
<?php if ( $wp_query->current_post == 1 ) { ?>
<div>Put Ad Here</div>
<?php } ?>
<?php endwhile; endif; ?>
我将该代码添加到归档-product.php
中,如下所示:
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
/**
* Hook: woocommerce_shop_loop.
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
if ( $wp_query->current_post == 1 ) {
echo '<div>Put Ad Here</div>';
}
}
}
但它什么也没显示出来。 而且如果有一种方法可以添加这些内容,而完全不需要接触模板文件,那就太好了。
有没有我可以用的钩子?
Updated-不是重写模板文件,您可以使用以下挂钩函数,它将在每个产品行之间添加一个自定义内容整行:
add_action( 'woocommerce_shop_loop', 'action_woocommerce_shop_loop', 100 );
function action_woocommerce_shop_loop() {
// Only on producy cayegory archives
if ( is_product_category() ) :
global $wp_query;
// Get the number of columns set for this query
$columns = esc_attr( wc_get_loop_prop( 'columns' ) );
// Get the current post count
$current_post = $wp_query->current_post;
if ( ( $current_post % $columns ) == 0 && $current_post > 1 ) :
?>
</ul>
<ul class="columns-1" style="list-style:none; margin:0 0 3em;">
<li style="text-align:center; padding:2em 1em; border: solid 1px #ccc;"><?php _e("Custom content here"); ?></li>
</ul>
<ul class="products columns-<?php echo $columns; ?>">
<?php
endif; endif;
}
代码放在活动子主题(或活动主题)的functions.php文件中。 经过测试并正常工作。