这不是我第一次用Wordpress坚持这个......这就是事情:我想拥有一个
-
a "portfolio"页面(设置为首页)显示最后16个具有标签组合的帖子
-
a "blog"页面显示最后XX(WP默认)帖子 .
我读了很多关于查询,头版,家庭等等,我的结论是我应该
-
构建两页
-
使用自定义设计为每个模板分配不同的模板
-
不为此制作custom query in my template;因为它会打破分页:例如,next_posts_link()将不会显示任何内容,因为它基于主查询,而不是自定义查询 .
强烈建议您使用pre_get_posts过滤器而不是query_posts(),并通过检查is_main_query来更改主查询
所以,as recommanded in the codex,我决定在functions.php中过滤pre_get_posts,而不是直接在投资组合模板中使用wp_query(...) .
add_action( 'pre_get_posts', 'cargo_portfolio' );
然后我设置了一些条件来检查我是否在正确的页面上:
function cargo_portfolio( $query ) {
if (!$query->is_main_query() ) return;
if ( $query->get( 'page_id' ) && ( $query->get( 'page_id' ) == 128 )){ //128 is my portfolio page
//edit query here
}
}
我不想使用静态数字(128),所以我发现了这个(组合/首页的代码)
function cargo_portfolio( $query ) {
if (!$query->is_main_query() ) return;
//check is static home page, since is_front_page() is not working yet at this level
if ( $query->get( 'page_id' ) && ( $query->get( 'page_id' ) == get_option( 'page_on_front' ) )){
//edit query here
}
}
我开始使用以下代码编辑查询:
$query->set( 'page_id', null );
$query->set( 'post_type', 'post' );
$query->set( 'tag', 'portfolio' );
$query->set( 'showposts', 16 );
所以我最终得到了这个功能:
function cargo_portfolio( $query ) {
if (!$query->is_main_query() ) return;
//check is static home page, since is_front_page() is not working yet at this level
if ( $query->get( 'page_id' ) && ( $query->get( 'page_id' ) == get_option( 'page_on_front' ) )){
$query->set( 'page_id', null );
$query->set( 'post_type', 'post' );
$query->set( 'tag', 'portfolio' );
$query->set( 'showposts', 16 );
}
}
好 . 谢谢阅读... :)
这里的问题是,我取消设置 page_id 并更改 post_type 变量(因为我想获取帖子),并且它会破坏查询 . 现在我登陆404页面 .
有谁有一个很好的解决方案来实现这一目标在此之前,我使用的是The Loops plugin,但它已经有2年没有更新并且已经破损 . :我确信应该有一个简单的方法来做到这一点 .
非常感谢 !!!
1 回答
最后,我最终直接在模板中使用自定义查询 .
可以通过向其添加查询参数来使用分页 functions get_next_posts() 和 get_previous_posts() ,请参见此处:
Wordpress pagination (next_posts_link) on custom wp_query not showing .
谢谢 !