Dashicon My CPTs on the Dashboard

To extend on what I said about how my custom post types are in mu-plugins, and knowing that I like MP6 a lot, I thought I should share how I style my icons for CPTs!

First off, the code to add tables has changed totally so I made this simple look to go through my CPTs (ebooks and plugins) and for each one, make a new item, and add that to dashboard_glance_items:

    // Adding to Right Now
    	add_action( 'dashboard_glance_items', 'halfelf_right_now' );
     
    	function halfelf_right_now() {
        	foreach ( array( 'ebooks', 'plugins' ) as $post_type ) {
        		$num_posts = wp_count_posts( $post_type );
        		if ( $num_posts && $num_posts->publish ) {
        			if ( 'ebooks' == $post_type ) {
        				$text = _n( '%s eBook', '%s eBooks', $num_posts->publish );
        			} 
        			if ( 'plugins' == $post_type ) {
        				$text = _n( '%s Plugin', '%s Plugins', $num_posts->publish );
        			}
        			$text = sprintf( $text, number_format_i18n( $num_posts->publish ) );
        			printf( '<li class="%1$s-count"><a href="edit.php?post_type=%1$s">%2$s</a></li>', $post_type, $text );
        		}
        	}
    	}

Next I added in an extra function to the bottom of my CPT page for the styling:

    function helf_cpts_css() {
       echo "<style type='text/css'>
               #adminmenu #menu-posts-ebooks div.wp-menu-image:before, #dashboard_right_now li.ebooks-count a:before {
                    content: '\\f311';
                    margin-left: -1px;
                }
               #adminmenu #menu-posts-plugins div.wp-menu-image:before, #dashboard_right_now li.plugins-count a:before {
                    content: '\\f237';
                    margin-left: -1px;
                }
             </style>";
    }
    
    add_action('admin_head', 'helf_cpts_css');

No, really, that’s it. The content info is grabbed from Dashicons and I’m done. Oh and since there’s no book icon, I used dashicons-welcome-learn-more instead. This works for anything I chose to put in Right Now or my menu, so I have consistency.

6 thoughts on “Dashicon My CPTs on the Dashboard

  1. Yup, that’ll do nicely! Hadn’t even noticed my CPTs not on my dash in one of my lesser used sites until you mentioned it. But now it’s all fixed, so thanks!

  2. The other day I wrote a post over at my site (linked via my name) on how to accomplish the same, but in a different way than you do.

    When registering the CPT you can simply replace the menu_icon call to an image with the dashicon of your choice: ‘menu_icon’ => ‘dashicons-wordpress’.

Comments are closed.