Wordpress WP_Query result array

我正在尝试使我的wordpress主页仅显示2篇博客文章。具有不同的显示元素。其中一个是向左浮动,一个是向右浮动。在原生php上,很容易将结果获取为数组。并使用 和 打印它们。$result[0]$result[1]


但是在wordpress idk上可以做到这一点。也许你们可以帮助我指导任何文档。比如wp_query等,别忘了给我一个示例代码行


*对不起,我的英语太差了。我希望你们阅读并回复。


我目前的代码行是:


$blogposts = new WP_Query(array(

        'post_type' => 'post',

        'posts_per_page' => 2,

    ));

while ($blogposts->have_posts()) {

        $blogposts->the_post();


}


茅侃侃
浏览 147回答 1
1回答

神不在的星期二

如果你对数组更满意,你总是可以使用get_posts()函数,它(几乎)像WP_Query()类一样接受参数。 实际上也利用了。get_posts()WP_Query也就是说,正如你所提到的,使用“本机PHP”修改你的代码并不困难。它只是一个&nbsp;while&nbsp;循环,而不是&nbsp;foreach&nbsp;循环,两者都是类似的控制结构。您所要做的就是添加一个计数器变量,并在每次通过后使用增量运算符递增它:++;下面是一个快速代码示例:$args = array(&nbsp; &nbsp; 'posts_per_page' => 2,);$query = new WP_Query( $args );if( $query->have_posts() ){&nbsp; &nbsp; $count = 0; // Start a Counter&nbsp; &nbsp; while( $query->have_posts() ){&nbsp; &nbsp; &nbsp; &nbsp; $query->the_post();&nbsp; &nbsp; &nbsp; &nbsp; printf( '<div class="post float-%s">', ($count++ % 2 == 0) ? 'left' : 'right' ); // If counter is odd: "left", even: "right"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf( '<h4 class="post-title">%s</h4>', get_the_title() );&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; the_content();&nbsp; &nbsp; &nbsp; &nbsp; echo '</div>';&nbsp; &nbsp; }} else {&nbsp; &nbsp; echo 'No Posts Found.';}几件事:我将数组移动到它自己的变量。有些查询可能会变得非常复杂,将它们作为指定变量可以提高长期可维护性。$args如果您只想,也不需要参数,因为这是默认值。post_typepost我添加了一个子句,所以如果你的帖子消失了,或者你移动了这个代码,就会有一个“没有找到”的回退。if我在后期类中使用了一些复杂的三元运算符。我在那里递增它,这样我们就不需要另一行来递增后面的行,并且它消除了对多行“if/else”来确定或.$countleftright除此之外,你没有提供标记结构,所以我使用了一个the_,如果你没有意识到其中的区别,get_the_函数。
打开App,查看更多内容
随时随地看视频慕课网APP