简体   繁体   中英

How to separate posts from WP_Query into 2 columns

I need to separate posts from WP_Query into 2 columns: first post will go to right column, 3 other posts will go to left column so the structure will look like this - https://prnt.sc/vc044d Please help me to improve my code. Thanks a lot.

function mk_latestposts() {

// the query

$the_query = new WP_Query( array( 'posts_per_page' => 4 ) ); 


// The Loop
if ( $the_query->have_posts() ) {
    $postcount = 0;
    $string .= '<ul class="mk-recent-posts-list">';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $postcount++;

            // if this is the first post
            if ( $postcount == 1 ) {
            $string .= '<li class="first-post">';
            $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() . get_the_date() .'</a></li>';
            } else { 

            // if this is the next post
            $string .= '<li class="next-post">';
            $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() . get_the_date() .'</a></li>';
            }
            }
    } else {

    // no posts found
}

$string .= '</ul>';
return $string;

/* Restore original Post Data */
wp_reset_postdata();
}

// Add a shortcode
add_shortcode('mklatestposts', 'mk_latestposts');

Your code is fine You can do this with CSS. Just add a common class to every <li> Like <li class='single-post'> and then apply this CSS. You can change it from List structure to Div structure whatever you want.

li.single-post{ width: 47%; float: left;} ul.mk-recent-posts-list { width: 100%; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM