Pass IDs to pre_get_posts query in function

后端 未结 2 929
滥情空心
滥情空心 2021-01-27 04:15

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\' );

func         


        
相关标签:
2条回答
  • 2021-01-27 04:53

    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,"
    )
    

    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"
    )
    

    And actually that's what get_col() returns, so you just need to pass $results to set() function:

    $query->set ( 'post__in', $results );
    

    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...

    0 讨论(0)
  • 2021-01-27 04:56

    Except the extra array() over $results_separated, in my case I had to apply

    if (!$query->is_main_query()) {
        return $query;
    }
    

    at the top of my function (found it in, otherwise, queries inside would be executed for several times and not properly. Comments in the answer helped me to figure this out.

    0 讨论(0)
提交回复
热议问题