How do I print a notice only on certain admin pages?

I’m writing a plugin which would print a notice, but only on the media page. I found the admin_notices and all_admin_notices actions, but these are fired on all admin pages. Is there any way to find which admin page is the hook being called on from within the callback?

Related posts

2 comments

  1. There is a global variable called $pagenow for the use within WP Admin:

    global $pagenow;
    if ( $pagenow == 'upload.php' ) :
    
        function custom_admin_notice() {
            echo '<div class="updated"><p>Updated!</p></div>';
        }
        add_action( 'admin_notices', 'custom_admin_notice' );
    
    endif;
    

    UPDATE: Simply include the snippet in your themes or plugins functions.php

  2. An alternative way is using the load-{$page} hook.

    Example:

    add_action('load-edit.php', 'maybe_edit_notice'); // only on edit.php paged
    
    function maybe_edit_notice() {
      // some example notices based on the get variables
      // the url should be something htt://example.com/wp-admin/edit.php?done=1&error=1
      if ( isset($_GET['done']) ) {
        $message = isset($_GET['error']) ? 'There was an error.' : 'Everithing ok.';
        $class = isset($_GET['error']) ? 'error' : 'updated';
        global $my_notice_args;
        $my_notice_args = compact('message', 'class');
        add_action('admin_notices', 'print_my_notice');
      }
    }
    
    function print_my_notice() {
      global $my_notice_args;
      if ( ! empty($my_notice_args) ) {
        printf('<div class="%s"><p>%s</p></div>', $my_args_notice['class'], $my_args_notice['message']);
      }
    }
    

    See ‘admin_notices’ hook docs on Codex

Comments are closed.