Answering my own question seems weird, but here is how I was able to achieve it –
function filter_posts_by_id($query) {
if ( !is_admin() && is_post_type_archive('CPT_NAME') && $query->is_main_query()) {
$post_ids = $_GET['post_ids'];
if(!empty($post_ids)) {
$pids = explode(',',$_GET['post_ids']);
$query->set('post__in', $pids);
}
}
}
add_action('pre_get_posts', 'filter_posts_by_id');
- PHP’s predefined variable $_GET[‘parameter’] to get the query string
- PHP’s explode() to convert comma-seperated query string to an array of post ids
- WordPress WP_query function $query->set(‘parameter’,$value) to set the wp query with the post_id filter
- Added the function to function.php of the theme and hooked with pre_get_posts so that the function runs before querying.
- Additionally set is_post_type_archive(‘post_type_name’) to specifically target my CPT
Hope it helps others who got stuck there! This is the first time I am playing with Queries, so the code might not be the best.