How to check if I’m on a custom post type archive in the admin area

Here are three possibilities, based on the /wp-admin/admin.php file:

Method #1

There are the global $pagenow and $typenow available:

    global $pagenow, $typenow;
    if( 'my_venue' === $typenow && 'edit.php' === $pagenow )
    {
        // ...
    }

Method #2

Then there’s the current screen, also set in the admin.php file with set_current_screen();

    $screen = get_current_screen();
    if( is_a( $screen, '\WP_Screen') && 'edit-myvenue' === $screen->id );
    {
        // ...
    }

where we use the id property of the \WP_Screen object.

If we skim through the \WP_Screen class, we find the current_screen hook, that might be used instead:

add_action( 'current_screen', function( \WP_Screen $s )
{
    if( 'edit-myvenue' === $s->id )
    {
        // ...
    }
} );

Method #3

Then there’s the load-edit.php hook, that’s available prior to the pre_get_posts hook:

add_action( 'load-edit.php', function()
{
    // Check for the post type here.
} );

In this case, the general hook is load-$pagenow. No need for the is_admin() check here.

Note

If you’re targetting the main query, then you should add $query->is_main_query() check as well within your pre_get_posts callback.

Also remember to validate the $_GET['my_venue_ids'] part, it might not even exist in the $_GET array.

Nothing new here! I think we’ve all seen these methods, in one way or another, used in many questions & answers here on WPSE 😉

Leave a Comment

error code: 523