Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

php - Add content in between product rows in WooCommerce archives

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

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.

Is there an hook I could use for that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...