Insert a div after the 3rd product in woocommerce

2019-08-02 02:49发布

问题:

I am using 3 columns grid in woocommerce shop

[] [] []
[] [] []
[] [] []

How can I insert a div after the 3rd grid

Something like this

[][][inserted div]
[][][]
[][][]

So I can put anything in there, thanks.

回答1:

All the product loaded from a loop script just initiate any $variable= 0 and after every product loaded $variable incremented by 1 and check $variable %3 == 0 if success add the div

e.g.

$variable = 0;

{ //product loop start 

//product load

$variable ++; // variable increment
if($variable%3 == 0){
// Add Div here
}
} //product loop end


回答2:

you can achieve this by using jQuery also,

Try the CSS selector :nth-child():

$("#holder > div:nth-child(2)").after("<div>add div</div>");


回答3:

You can place this inside your post loop just before the loop ends. It will output your desired div (ad) after the 2nd post. Just make sure you add in any necessary CSS classes to the div, and of course your ad code or image.

<?php if ( $wp_query->current_post == 1 ) { ?>

  <div>Put Ad Here</div>

<?php } ?>

So it should look something like this within your post loop:

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

This works by using the $current_post property of the WP_Query class. It retrieves the index of your current post in the loop.

Hope this helps!