简体   繁体   中英

pass post ids to pre_get_posts query post__in function

I want to let the function return the posts by the query->set with post ids post__in, But the function returns nothing. Here is the code:

add_action( 'pre_get_posts', 'query_booked_posts' );

function query_booked_posts( $query ) {
global $post,$wpdb;

$current_user_id = get_current_user_id();
if ( is_page(21) ) { //the condition, work fine

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

$query->set ('post__in', array($results)); // pass results (post ids) to post__in

return $query;
}

}

Thanks

Jason

Please try this instead:

add_action( 'pre_get_posts', 'query_booked_posts' );

function query_booked_posts( $query )
{
    if ( is_page( 21 ) && is_user_logged_in() &&  $query->is_main_query() )
    {
        global $wpdb;
        $results = $wpdb->get_col( $wpdb->prepare( 
                   "SELECT booked_id FROM $wpdb->userbooking 
                    WHERE userid = %d",
                    get_current_user_id() ) );

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

where I replaced:

  • your undefined $condition with is_user_logged_in() .
  • the undefined $get_current_user_id with get_current_user_id() .
  • the extra array around $results , since the get_col method returns an array.
  • the is_home() check since you also use is_page(21) .

Hope it helps.

You might also need

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

if you'll find some strange results. I have found this by the link to similar question in the answer's comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM