进一步升级:只构建了一个类来放置函数。php或插件。我这样做主要是因为我希望几乎总是有粘性帖子,可能每页都有更多的循环。所以有很多重复。因此,这里有一个基本类,当然可以通过某种方式进行扩展/完善,但对于我的需求来说,它只起作用:
class Posts_With_Sticky{
public $max_items_amount;
public $normal_items_amount;
public $category;
public $sticky_ids;
public $sticky_query;
public $normal_query;
function __construct($category = null, $max_items_amount = 5){
$this->max_items_amount = $max_items_amount;
$this->sticky_ids = get_option(\'sticky_posts\');
$this->category = $category;
$this->get_query();
}
public function get_query(){
//sticky query
if(count($this->sticky_ids) != 0){
$this->sticky_query = new WP_Query();
$this->sticky_query->query(array(
\'category_name\' => $this->category,
\'posts_per_page\' => $this->max_items_amount,
\'post__in\' => $this->sticky_ids
));
}
//check amount of stikies and room for normals
if(isset($this->sticky_query)){
$stikies = count($this->sticky_query->posts);
if($stikies == $this->max_items_amount) return;
else $this->normal_items_amount = $this->max_items_amount - $stikies;
}
//normal posts query
$this->normal_query = new WP_Query();
$this->normal_query->query(array(
\'category_name\' => $this->category,
\'posts_per_page\' => $this->normal_items_amount,
\'post__not_in\' => $this->sticky_ids
));
}//end get_query
public function render_posts($sticky_loop_function,
$normal_loop_function = "",
$before_markup = "",
$after_markup = ""){
if(!$sticky_loop_function) return;
//shortcut
$sticky_setted = isset($this->sticky_query);
$normal_setted = isset($this->normal_query);
if(!$sticky_setted && !$normal_setted) return;
$sticky_loop = $sticky_loop_function;
$normal_loop = ($normal_loop_function !== "") ? $normal_loop_function : $sticky_loop_function;
echo $before_markup;
if($sticky_setted) $sticky_loop($this->sticky_query);
if($normal_setted) $normal_loop($this->normal_query);
echo $after_markup;
}//end render_posts
}//end Posts_With_Sticky
然后,在html页面中,我将为每个部分编写不同的循环函数,然后将其传递给render\\u posts()。
类似这样:
<?php
//html output function
function write_soon_items($query){
while($query->have_posts()){
$query->the_post();
$date = get_the_date(\'d.m.Y\');
$title = get_the_title();
$excerpt = get_the_excerpt();
$link = get_permalink();
echo <<< ITEM_BLOCK
<article>
<h4>
$date - $title
</h4>
<p>
<a href="$link" title="$title">$excerpt</a>
</p>
<div class="float-reset"></div>
</article>
ITEM_BLOCK;
}
}//end write_sub_items
$soon_posts = new Posts_With_Sticky(\'coming-soon\');
$soon_posts->render_posts(\'write_soon_items\')
?>
因此,每当我需要一个循环来纪念某个类别的粘性帖子时,我只需使用\\u sticky实例创建另一个posts\\u,然后调用其render\\u posts()方法来传递自定义输出循环函数。
请注意,可以传递render\\u posts()一个用于粘滞的函数、一个用于法线的函数(如果不传递,将使用第一个)、一个“before\\u markup”和一个“after\\u markup”。
希望它能帮助别人。
再见