这与此相关other question, 我试过了get_posts
, pre_get_posts
, WP_Query
基本上,我能找到的每一个选择都持续了2天,目前还没有解决方案。
目前的全部问题是:我有两种帖子类型,articles
和news
. “新闻”中的帖子可以是“特色”或“非特色”。我需要查询1条特色新闻、4篇文章和2条非特色新闻,并按此顺序显示在页面上。页面使用page-mypage.php
样板
帖子需要按照特定的顺序排列,因为帖子的大小取决于类型和“特色”元选项。我的网格是用砖石砌成的,为了有一个完整的网格(没有洞或奇怪的空白)的顺序是featured, article, article, article, article, non-featured, non-featured
.
使用get_posts
在另一个问题中,我无法实现分页。当导航到/page/X
但我尝试了一系列定制分页解决方案,但都没有成功paginate_links
我也不能去工作。
所以现在我想用WP_Query
但是,我如何告诉WordPress我希望每个帖子类型都有那么多帖子,并且按照特定的顺序排列?
这是我真正想做的,但我似乎找不到一种方法WP_Query
要使分页正常工作(该死的分页!):
$articles = get_posts(array(
\'post_type\' => \'articles\',
\'numberposts\' => 4
));
$featured = get_posts(array(
\'post_type\' => \'news\',
\'numberposts\' => 1,
\'meta_query\' => array(
array(
\'key\' => \'featured-news\',
\'value\' => \'Yes\',
\'compare\' => \'LIKE\'
)
)
));
$non_featured = get_posts(array(
\'post_type\' => \'news\',
\'numberposts\' => 2,
\'meta_query\' => array(
array(
\'key\' => \'featured-news\',
\'value\' => \'No\',
\'compare\' => \'LIKE\'
)
)
));
// Merge in the order I need them to appear
$all_posts = array_merge($featured, $articles, $non-featured);
// The loop
暂停!。
最合适的回答,由SO网友:revo 整理而成
您可以使用WP_Query()
具有paged
传递当前页码的数组键:
<?php
$paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
$args = array(
\'post_type\' => \'articles\',
\'posts_per_page\' => 4,
\'paged\' => $paged
);
$articles = new WP_Query($args);
////////////////////////////////
$args = array(
\'post_type\' => \'news\',
\'posts_per_page\' => 1,
\'meta_query\' => array(
array(
\'key\' => \'featured-news\',
\'value\' => \'Yes\',
\'compare\' => \'LIKE\'
)
),
\'paged\' => $paged
);
$featured = new WP_Query($args);
////////////////////////////////
$args = array(
\'post_type\' => \'news\',
\'posts_per_page\' => 2,
\'meta_query\' => array(
array(
\'key\' => \'featured-news\',
\'value\' => \'No\',
\'compare\' => \'LIKE\'
)
),
\'paged\' => $paged
);
$non_featured = new WP_Query($args);
////////////////////////////////
$articles = objectToArray($articles); // objectToArray() function defines below
$featured = objectToArray($featured);
$non_featured = objectToArray($non_featured);
$all_posts = array_merge($featured, $articles, $non_featured);
?>
而且,由于您正在查询3种帖子类型,分页将失败,因为它不知道应该基于哪种帖子类型分页!
您可以使用手动分页:
<?php
// $paged = (get_query_var(\'paged\')) ? get_query_var(\'paged\') : 1;
if($paged > 1)
{
echo "<a href=\\"".home_url(\'/\')."/page/".($paged-1)."\\">Previous page</a>";
}
echo "<a href=\\"".home_url(\'/\')."/page/".($paged+1)."\\">Next page</a>";
?>
也许您需要将HREF attr更改为其他内容。
Which I forgot:
<?php
function objectToArray($d) {
if (is_object($d)) {
$d = get_object_vars($d);
}
if (is_array($d)) {
return array_map(__FUNCTION__, $d);
}
else {
return $d;
}
}
?>
WP\\u Query返回stdClass对象,首先应将其转换为如下数组:
<?php
$articles = objectToArray($articles);
$featured = objectToArray($featured);
$non_featured = objectToArray($non_featured);
?>
然后合并它们。(以上更新代码)
Updated
另一种简便的方法是合并stdClass对象:
https://stackoverflow.com/a/1953077/1906508