- I have a custom query for a CPT, from which I can obtain an array of postid's.
- I want a url to the archive of the CPT, which has the query result (i.e. the posts of the postid's in the array are shown).
- This url needs to go in a button as href value.
-
There aren’t standard URLs for an arbitrary list of IDs. What is the criteria you’re using to get these ids?– Jacob PeattieCommented Mar 8, 2018 at 15:20
-
Actually its a pretty complex and referential series of queries (query from a post type -> list of linked taxonomy -> another query of the req. post type -> post_id array), a query inside query, i know it sounds weird.– aswinshenoyCommented Mar 8, 2018 at 15:28
-
But can't we make a function to do that? something like "abc.xyz/posttype/?post_id=534,323. I can do a bit of coding, but dont know where to start.– aswinshenoyCommented Mar 8, 2018 at 15:28
-
@JacobPeattie I want something like this wp-types.com/documentation/user-guides/…– aswinshenoyCommented Mar 8, 2018 at 15:38
-
You'd need to edit the theme file for that CPT's archive so that it can accept your custom query string, parse it, and run a custom query.– WebElaineCommented Mar 8, 2018 at 20:50
|
Show 1 more comment
1 Answer
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.