在WooCommerce档案中的产品行之间添加内容 [英] Add content in between product rows in WooCommerce archives

查看:136
本文介绍了在WooCommerce档案中的产品行之间添加内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在某个产品类别的第三个产品(也许是第六个,第九个...)之后显示一些内容.并非每个类别都具有该额外内容或相同数量的内容.因此,它应该很灵活.

I want to show some content after the third product (and maybe the sixth, ninth...) of a product category. Not every category has that extra content or the same amount of it. So it should be flexible.

我找到了一个示例,该示例使用以下代码:

I found an example which uses the following code :

<?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; ?>

我将代码添加到我的archive-product.php中,如下所示:

I added that code to my archive-product.php like this:

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>';
        }


    }
}

但是它什么也没显示. 并且,如果有一种方法可以添加这些内容而完全不触碰模板文件,那就太好了.

But it doesn't show anything. And it would be nice if there is a way to add these content without touching the template file at all.

我可以用一个钩子吗?

推荐答案

已更新-除了覆盖模板文件之外,您还可以使用以下挂钩函数,该函数将在其中添加自定义内容完整行每个产品行之间:

Updated - Instead of overriding a template file, you can use the following hooked function, that will add a custom content full row in between each products row:

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;
}

代码进入您的活动子主题(或活动主题)的functions.php文件中.经过测试,可以正常工作.

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

这篇关于在WooCommerce档案中的产品行之间添加内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆