How to do a query only on a specific admin page?

It’s worthwhile pointing out that using admin_init within the current_screen filter is too late because admin_init has already fired.

Instead do:

add_action('current_screen', 'current_screen_callback');

function current_screen_callback($screen) {
    if( is_object($screen) && $screen->id === 'top_level_custom-settings-api' ) {
        add_filter('top_level_screen', '__return_true');
    }
}

Elsewhere in your top_level_page_callback callback responsible for executing the query:

function top_level_page_callback() {

    $active_posts = null;

    if ( ($is_top_level = apply_filters('top_level_screen', false)) ) {

        $active_posts = pre_get_active_posts_of_30_days();

    }

    //etc...

}

That’s one way to do it…

Or you could use, add_action('load-top_level_custom-settings-api', 'callback');

Other than the current_screen hook, where else were you trying to call pre_get_active_posts_of_30_days() from? Because you had to have been calling it in a global scope of some sort for it to be running on all pages and not just the target page.

Leave a Comment