我试图在显示单个页面时更改主查询,以返回另一个页面。我认为这是query\\u posts()永久更改主查询的少数情况之一,但在许多情况下,我仍然会得到原始的post IDget_the_ID()
诸如此类。
实现这种看似简单的页面请求更改的正确时机(动作挂钩)和方法是什么?
示例:每当请求页面ID 5时,请加载页面ID 10。
我试图在显示单个页面时更改主查询,以返回另一个页面。我认为这是query\\u posts()永久更改主查询的少数情况之一,但在许多情况下,我仍然会得到原始的post IDget_the_ID()
诸如此类。
实现这种看似简单的页面请求更改的正确时机(动作挂钩)和方法是什么?
示例:每当请求页面ID 5时,请加载页面ID 10。
如果您可以访问帖子的ID,则表示查询已经运行。因此,在这种情况下,您不能使用pre_get_posts
不再
解决方案是将代码包装在条件中,然后使用以下函数get_the_permalink()
或get_the_title()
接受帖子ID以获取其他帖子的内容:
if( get_the_ID() == \'5\' ){
get_the_title( 10 );
} else {
// Main loop
}
以上内容应在模板中使用。另一种合理且更好的方法是使用重定向。检查帖子的ID,如果条件匹配,则重定向用户:
if( get_the_ID() == \'5\' ) {
wp_safe_redirect( get_the_permalink( 10 ) );
exit();
}
这可以用于functions.php
或模板的标题。还有一个黑客,你可能想使用,以获得pre_get_posts
工作。
add_action( \'pre_get_posts\', \'my_function\' );
function my_function( $query ) {
// Remove this action hook so we don\'t go into an infinite loop
remove_action( \'pre_get_posts\', \'my_function\' );
// Get a list of posts belonging to this query
$posts = get_posts( $query->query );
// If there is only one post in the array and its ID matches
// what we\'re looking for, then we can alter the main query
if( $query->is_main_query() && sizeOf( $posts ) == \'1\' && $post[0]->ID == \'5\' ) {
// Now we can modify the query here
}
}
我对这一点非常陌生,我想做的只是不限制主页上列出的帖子数量。它目前只显示了大约32个帖子中的20个,因此所有旧帖子都不再显示。有没有一种简单的方法可以使最近的帖子下显示的帖子数量不受限制,甚至99个?