将ID传递给函数中的pre_get_posts查询 [英] Pass IDs to pre_get_posts query in function
问题描述
$ b
I am trying to pass the post ids to the function's query->set and function will return the posts.
add_action( 'pre_get_posts', 'query_booked_posts' );
function query_booked_posts( $query ) {
if ( $condition ) { //the condition
if ( is_home() && $query->is_main_query() )
$results = $wpdb->get_col($wpdb->prepare( "SELECT booked_id FROM $wpdb->userbooking WHERE userid = %d",$current_user_id));
foreach($results as $result){
$results_separated = $result.',';
}
$query->set ('post__in', array($results_separated)); // pass results (post ids) to post__in
return $query;
}
}
我试图将post id传递给函数的query-> set并且函数会返回帖子。 ('pre_get_posts','query_booked_posts');
函数query_booked_posts($ query){
if($ condition){//条件
if(is_home()&& $ query-> ; $ is_main_query())
$ results = $ wpdb-> get_col($ wpdb-> prepare(SELECT booked_id FROM $ wpdb-> userbooking WHERE userid =%d,$ current_user_id));
foreach($ results as $ result){
$ results_separated = $ result。',';
$ query-> set('post__in',array($ results_separated)); //将结果(post ID)传递给post_in
return $ query;
}
}
After this, the function returns nothing.
在此之后,该函数不会返回任何内容。
If I do $query->set ('post__in', array(45,121));
, the query will return the posts of id 45 and id 121, so the query works fine.
如果我做了 $ query-> set('post__in',array(45,121));
,查询将返回id 45和id 121的帖子,所以查询工作正常。
But I want to make $results_separated
pass the post ids like 45,121,132 to the query, and then $query->set ('post__in', array($results_separated));
will work correctly.
How can I make this happen?
但是我想让 $ results_separated
将post标识符45,121,132传递给查询,然后将 $ query-> set('post__in',array($ results_separated));
正常工作。
我该如何做到这一点?
pre_get_posts
reference
推荐答案
实际上有一个PHP问题。当你做 array($ results_separated)
时,你基本上是用一个字符串来创建一个数组,如下所示:12,114,56 code>。通过这样做,PHP正在创建一个这样的数组:
I guess you have actually a PHP problem. When you do array($results_separated)
you're basically creating an array from a string that looks like this: "12,114,56,"
. By doing that, PHP is creating an array like this:
array(
0 => "12,114,56,"
)
显然,WordPress无法找到这样的ID的任何帖子!你想要的实际上是一个这样的数组:
And obviously WordPress cannot find any posts with such ID! What you want is actually an array like this:
array(
0 => "12",
1 => "114",
2 => "56"
)
实际上这就是 get_col()
返回的结果,所以你只需要将 $ results
传递给 set()
函数:
And actually that's what get_col()
returns, so you just need to pass $results
to set()
function:
$query->set ( 'post__in', $results );
编辑 :其实我意识到你的问题是当你调用 $ wpdb-> get_col(...)
时,因为它干扰了 $ query
你会稍后执行...这些变量使用了一些其他可能被重写的全局变量,这就是为什么你没有得到任何结果...
EDIT: Actually I realised that your problem is when you call $wpdb->get_col(...)
, because it's interfering with the $query
you will execute later on... Those variables are using some other global variables that probably get overriden, and that's why you're not getting any results...
这篇关于将ID传递给函数中的pre_get_posts查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!