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

I am trying to alter the query that’s ran on the admin page of my custom post type. This page: /wp-admin/edit.php?post_type=my_venue. Typically, I would use is_admin() && is_post_type_archive('my_venue') to check if I’m on the correct page before modifying the query. However, I have registered my post type with 'archive' => false so now is_post_type_archive() always returns false.

What’s the best way to modify the query only for this page?

register_post_type(
    'my_venue',
    [
        'has_archive' => false,
    ]
);

add_action('pre_get_posts', 'my_venue_filters');

function my_venue_filters($query) {
    if (is_admin() && is_post_type_archive('my_venue')) {
        if (!empty($_GET['my_venue_ids'])) {
            $query->set('post__in', $_GET['my_venue_ids']);
        }
    }
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 😉


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x