How to add some custom HTML into wordpress admin bar?

You’re right on track with the work that needs to be done, and WordPress makes is really simple to accomplish what you’re going for.

The hook that you’re looking for is called admin_bar_menu. You can read more about it and the WP_Admin_Bar class here.

The other step to get the post count could be done in a few ways, but I’ve used WP_Query below. Another powerful class that you’ll want to get familiar with.

Here’s some sample code that will get you in the right direction.

add_action( 'admin_bar_menu', 'wpse_admin_bar', 900 );
// The first argument is the name of the hook,
// the second is the callback function that you see below,
// and the 900 denotes the priority with which the hook is called
//This high number means this code will run later, and thus show up at the end of the list.

function wpse_admin_bar( $wp_admin_bar ){
    $args = array(
        //Type & Status Parameters
        'post_type'   => 'wpse_cpt',
        'post_status' => 'publish',
    );

    $wpse_cpt = new WP_Query( $args );

   $admin_bar_args = array(
      'id' => 'staff_count'
      ,'title' => 'XYZ Post:'.count($wpse_cpt->posts) // this is the visible portion in the admin bar.
      );

   $wp_admin_bar->add_node($admin_bar_args);
}

Leave a Comment