我有一个显示最新帖子的 WordPress 网站。它们以类似于以下的设计输出:
http://tienvooracht.nl/themes/elevate/
三列四行内容。这是我无法弄清楚的部分 - 无论类别如何,我如何拉出最新的帖子,但限制每行显示多少?
示例:我有类别、摄影、网页设计和 UI 设计。我碰巧连续写了 5 篇关于摄影的帖子,但我不希望我最近的所有帖子都是关于摄影的。
有没有办法限制显示单个类别的帖子数量,并在达到该限制后显示来自不同类别的其他帖子?
我有一个显示最新帖子的 WordPress 网站。它们以类似于以下的设计输出:
http://tienvooracht.nl/themes/elevate/
三列四行内容。这是我无法弄清楚的部分 - 无论类别如何,我如何拉出最新的帖子,但限制每行显示多少?
示例:我有类别、摄影、网页设计和 UI 设计。我碰巧连续写了 5 篇关于摄影的帖子,但我不希望我最近的所有帖子都是关于摄影的。
有没有办法限制显示单个类别的帖子数量,并在达到该限制后显示来自不同类别的其他帖子?
要限制特定类别的帖子,请使用此代码。
<?php
global $post;
$args = array( 'numberposts' => 5, 'category' => 3 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :
setup_postdata($post); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<?php endforeach; ?>
更改类别 ID 和帖子数量限制...
这个限制是静态的吗?一如既往。如果是这样,您可以在 WordPress 的阅读设置中进行设置。在主循环之前添加一个变量 $x=0; 然后在循环中添加 $x++; 然后像这样添加第二个查询。
<?php
$defaultPostsPerPage = 12;
$sndary = $defaultPostsPerPage - $x;
if($sndary > 0){
$y=0;
$args = array('post_type'=>'post','post_per_page'=>12);
$showcase = new WP_Query( $args );
if ( $showcase->have_posts() ) { while ( $showcase->have_posts() ) { $showcase->the_post(); ?>
<!-- post html css goes here as you would any other loop -->
<?php
if($y%4==0){
//add some sort of css line break, clear fix or last class on the element. to break to the new line.
}
} ?>
<!-- post navigation -->
<?php }else{ ?>
<!-- no posts found -->
<?php }
}
在这里,我们正在检查主查询中有多少帖子,如果它们低于每页的最大值,我们可以添加我们的辅助查询。这里唯一要注意的是我们没有考虑分页,但这不是问题的一部分。
<?php
/* create categories array and pass id of categories from which we want to show the posts*/
$categories=array(4,5,3);
foreach($categories as $cat){
global $post;
/* limit numberposts, here specified 2 and pass the categories dynamically in args array*/
$args=array('numberposts' =>2, 'category' =>$cat);
$myposts=get_posts($args);
foreach($myposts as $mypost){
echo "<h1>".$mypost->post_title."</h1> ".$mypost- >post_content." ".$mypost->post_modified;
echo "<br />";
}
}
?>