向默认$post查询Wordpress注入自定义参数
无论如何,我是否可以将自定义参数插入到在归档页面上返回$post的默认查询中 例如,在自定义存档上,我会执行以下操作:向默认$post查询Wordpress注入自定义参数,post,arguments,parameter-passing,wordpress,Post,Arguments,Parameter Passing,Wordpress,无论如何,我是否可以将自定义参数插入到在归档页面上返回$post的默认查询中 例如,在自定义存档上,我会执行以下操作: <?php while(have_posts()): the_post(); endwhile; ?> 那么,如何将say'orderBy'注入到该查询中,以便$post对象遵循该参数 -- 这是可能的,还是我自己创建并调用一个查询 多谢各位 Connor您也可以通过自定义查询进行调用。但最好的解决办法是在钩下使用 // Runs
<?php
while(have_posts()): the_post();
endwhile;
?>
那么,如何将say'orderBy'注入到该查询中,以便$post对象遵循该参数
--
这是可能的,还是我自己创建并调用一个查询
多谢各位
Connor您也可以通过自定义查询进行调用。但最好的解决办法是在钩下使用
// Runs before the posts are fetched
add_filter( 'pre_get_posts' , 'my_change_order' );
// Function accepting current query
function my_change_order( $query ) {
// Check if the query is for an archive
if($query->is_archive)
// Query was for archive, then set order
$query->set( 'order' , 'asc' );
**// for specific post type archive page only**
$query->set( 'post_type', 'my_post_type' );
// Return the query (else there's no more query, oops!)
return $query;
}
在function.php文件中添加上述代码
您还可以传递自定义帖子类型
$query->set( 'post_type', 'my_post_type' );
太棒了!但是,这将设置全局所有查询的顺序,对吗?我只需要在网站的一个页面上操纵顺序,因此,例如,如果我添加一个快速页面id检查,这是否足以只更改该页面的查询参数?再次感谢!您想将其用于自定义帖子类型吗?是的,我有一个用户的自定义帖子类型,并且我希望它们在默认情况下处于不同的顺序。但仅针对该特定存档,我并不希望它成为(have_posts()):the_post()的所有实例的全局查询参数;如果有道理的话。简单检查我的更新代码。您需要在if条件$query->set('post_type'、'my_post_type')中使用此选项;
<?php is_post_type_archive( $post_types ); ?>