首页 > 解决方案 > 如何将 WP_Query 中的帖子分成 2 列

问题描述

我需要将 WP_Query 中的帖子分成 2 列:第一个帖子将转到右列,其他 3 个帖子将转到左列,因此结构将如下所示 - https://prnt.sc/vc044d 请帮助我改进我的代码。非常感谢。

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');

标签: phpwordpress

解决方案


你的代码很好你可以用 CSS 做到这一点。只需为每个<li>Like添加一个公共类<li class='single-post'>,然后应用此 CSS。您可以根据需要将其从 List 结构更改为 Div 结构。

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

推荐阅读