I've created a few CPTs, and wish to have one of the custom post types to query from other post types.

So what I did is I used the codes below to alter the query:

add_filter('pre_get_posts', 'code_to_alter_query', 10);

function code_to_alter_query($query) {
  // If not backend, bail out
  if( !is_admin() ) return $query;

  $cpts = array('custom_job', 'custom_us_job');
  $query->set( 'post_type', $cpts );

  return $query;

Now it will show jobs from both custom_job and custom_us_job. But this will apply to both of the CPTs, what if I want only custom_job to have both jobs while custom_us_job to have the default query?

I tried using

global $pagenow;

But this can only get the edit.php which will be the same to all the CPTs, how can I determine which (admin) page am I in now?


The function you are looking for is get_current_screen(). To check if you are on a specific custom post type page, do as follows:

$screen = get_current_screen();
if ( $screen->post_type == 'custom_job' ) {
    // We are on custom_job post type, good to go

Now, if you visit edit.php?post_type=custom_job, this conditional will return true, which you can set your query inside.

There is also another approach for this. By using is_post_type_archive('custom_job'), you can target the edit.php?post_type=custom_job. Make sure you use this in conjunction with is_admin() to make sure you don't target the front-end.

  • But when I called get_current_screen(), it gets nothing, it returns an empty value. – Park Lai Jul 24 '17 at 8:05
  • I've updated the answer. @ParkLai – Jack Johansson Jul 24 '17 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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