How to add some custom HTML into wordpress admin bar?

I want to add some HTML (for showing count of specific type post in database)
Wordpress is new to me, I don’t have much knowledge about hooks and filters.

As i understand i need to do following work –

  1. Need to get count of post (XYZ type of post) from database.
  2. add a hook/filter to add these count in HTML of admin bar.

Can anyone, please help me to understand the process flow, and coding for above this work?

Note: I known, These type of question are not meet up with SO question standard. But really guys i don’t have much knowledge about this work.

I want something like this –
enter image description here

Thank you in advance…!!!

1
1

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