0
  1. I have a custom query for a CPT, from which I can obtain an array of postid's.
  2. 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).
  3. This url needs to go in a button as href value.
6
  • There aren’t standard URLs for an arbitrary list of IDs. What is the criteria you’re using to get these ids? Commented 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. Commented 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. Commented Mar 8, 2018 at 15:28
  • @JacobPeattie I want something like this wp-types.com/documentation/user-guides/… Commented 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.
    – WebElaine
    Commented Mar 8, 2018 at 20:50

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.