[英]Wordpress : pre_get_posts and passing arguments from author.php to function.php
I'm trying to get pre_get_posts to work with passing arguments. 我正在尝试使pre_get_posts与传递参数一起使用。 I have the following function in my function.php file of my theme.
我的主题的function.php文件中具有以下功能。
function cpt_on_author_page( $query, $user_id ) {
if ( $query->is_author() && $query->is_main_query() ) {
$query->set( 'post_type', 'programs' );
$query->set( 'posts_per_page', 1 );
$query->set( 'meta_key' , 'show_program_editors');
$query->set( 'meta_value' , $user_id);
}
}
add_action( 'pre_get_posts', 'cpt_on_author_page' );
I call this function via my author.php file via this code: 我通过以下代码通过author.php文件调用此函数:
do_action( 'pre_get_posts',$user_id );
On the output page, I am getting 在输出页面上,我得到
Missing argument 2 for cpt_on_author_page()
What am I doing wrong? 我究竟做错了什么?
Try changing line 1 to function cpt_on_author_page( $query ) {
尝试将第1行更改为
function cpt_on_author_page( $query ) {
If you need to use $user_id
(the ID of the current author) inside your function, you should be able to do something like this: 如果您需要在函数中使用
$user_id
(当前作者的ID),则应该可以执行以下操作:
$author = get_user_by( 'slug', get_query_var( 'author_name' ) );
$user_id = $author->ID;
You shouldn't need do_action( 'pre_get_posts',$user_id );
您不需要
do_action( 'pre_get_posts',$user_id );
at all. 完全没有
Update (after discussion in this answer's comments): 更新(在此答案的评论中进行讨论之后):
To show all posts having a meta value of kam
in kam
's author archive, you could do something like this: 为了显示其的meta值的所有帖子
kam
在kam
的作者的存档,你可以这样做:
function cpt_on_author_page( $query ) {
if ( $query->is_author() ) {
$users = get_users();
$ids = array();
foreach ( $users as $user ) {
$ids[] = $user->ID;
}
$query->set( 'author__in' , $ids );
$author = get_user_by( 'slug', get_query_var( 'author_name' ) );
$query->set( 'meta_value' , $author->user_login );
}
}
add_action( 'pre_get_posts', 'cpt_on_author_page' );
Notes: This assumes each author's nicename is the same as their username. 注意:这假设每个作者的好记的名字与其用户名相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.