Cra*_*ray 6 php wordpress product categories woocommerce
我想在产品类别的第三个产品(也许是第六个、第九个......)之后显示一些内容。并非每个类别都有额外的内容或相同数量的内容。所以应该是灵活的。
我找到了一个使用以下代码的示例:
<?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; ?>
Run Code Online (Sandbox Code Playgroud)
我将该代码添加到我的代码中,archive-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>';
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它没有显示任何东西。如果有一种方法可以在不接触模板文件的情况下添加这些内容,那就太好了。
有一个我可以用的钩子吗?
更新- 您可以使用以下挂钩函数,而不是覆盖模板文件,该函数将在每个产品行之间添加自定义内容完整行:
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;"><div class="banner"><?php _e("Custom content here"); ?></div></li>
</ul>
<ul class="products columns-<?php echo $columns; ?>">
<?php
endif; endif;
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。