• I have a PHP script that takes each WordPress post and assigns the post contents to a specific div (.col-1-6).

    These divs are then arranged in a grid.

    I have ten different posts (content divs) and I would like for them to show up on two rows. The first row should have six posts and the second row should have four.

    Right now, each row has five posts.

    Is there a way I can edit my PHP script to include the functionality I need?

    <?php
            $num_cols = 2; // set the number of columns here
            //the query section is only neccessary if the code is used in a page template//
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // for pagination
            $args = array(
                'posts_per_page' => 12, // optional to overwrite the dashboard setting
                'post_type' => 'graduate', // add any other query parameter to this array
                'paged' => $paged
    	);
            query_posts($args);
            //end of query section
    
            if (have_posts()) :
    
                for ( $i=1 ; $i <= $num_cols; $i++ ) :
                    echo '<div id="col-'.$i.'" class="preview">';
                    $counter = $num_cols + 1 - $i;
    
                    while (have_posts()) :
                        the_post();
    
                        if( $counter%$num_cols == 0 ) :
        ?>
    
        <div class="col-1-6">
    
        <?php
                            if ( has_post_thumbnail() ) {
                                // check if the post has a Post Thumbnail assigned to it.
                                the_post_thumbnail();
                            }
        ?>
    
            <a>" title="<?php the_title(); ?>"><p><?php the_title(); ?></p></a>
        </div>
    
        <?php
                        endif;
    
                        $counter++;
                    endwhile;
    
                    rewind_posts();
                    echo '</div>'; //closes the column div
    
                endfor;
    
            else:
                echo 'no posts';
            endif;
    
            wp_reset_query();
        ?>
Viewing 1 replies (of 1 total)
  • Right now, the code selects posts in this order:

    div col-1
       post 1
       post 3
       post 5
       post 7
       post 9
    end col-1
    div col-2
       post 2
       post 4
       post 6
       post 8
       post 10
    end col-2

    In other words, odd numbered posts go in the col-1 div, even numbered posts go in the col-2 div.

    If you want to show a specific maximum number of posts per div, the code would need to be heavily modified. Here is an article with some sample code that might help: https://wordpress.mcdspot.com/2010/11/28/align-posts-in-a-row/

Viewing 1 replies (of 1 total)
  • The topic ‘Using a loop to display content divs in a grid’ is closed to new replies.