0

I created a loop in my archive page displaying the posts in 3 columns (33% width) inside a row with 100% width. Each column is a post.

What I would like to achieve is to make the loop more flexible for smaller screens: 2 columns of 50% inside the row container for tablets then 1 column of 100% for mobiles. My main problem is, I need the posts inside the row container. So It would be: a row with 3 columns, then a row with 2 columns and a row with 1 column.

This is the code of the loop:

<!-- Start the Loop -->
<div class="row">
<?php while ( have_posts() ) : the_post(); ?>

  <?php get_template_part( 'template-parts/content', 'archive' ); ?>

  <?php if( $wp_query->current_post % 3 == 2 ) : ?>

 </div>
 <!-- row -->

 <div class="row">
 <?php endif; ?>

<?php endwhile; ?>

Any help would be much appreciated, thanks!

0

You can control this with media queries in CSS.

@media screen and (max-width: 768px) { div.row { width: 50%; } } /* for iPad */

@media screen and (max-width: 600px) { div.row { width: 100% } } /* for mobile phones */

I hope this helps.

UPDATE: You can't do this with PHP because PHP is executed on the server before the content is delivered to the browser, so there is no time for PHP to determine which device or viewport is in use. Have a look here.

3
  • Thanks for the help. However this is not what I'm trying to do. The row is already at 100%. What I would like to find is a PHP solution to reduce the number of posts per row from 3 to 2, then to 1. Jun 9 '20 at 9:23
  • You can't do this with PHP because PHP is executed on the server before the content is delivered to the browser, so there is no time for PHP to determine which device or viewport is in use. Have a look here: stackoverflow.com/questions/1504459/… Jun 9 '20 at 9:26
  • Thanks @mrcodefinger I will look into it. Jun 9 '20 at 9:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.