How to add Custom Post Type menu to Admin Sub-menu WordPress

July 15, 2014 by in category Programming, Wordpress with 0 and 1
Home > Blog > Programming > How to add Custom Post Type menu to Admin Sub-menu WordPress

After a lot of googling, I couldn’t find a solution to my problem. I finally figured it out and have decided to document it below.

<?php
  define("ICON_URL", '/path/to/icons');

  
  // First we sort out some submenu pages under our custom 
  // menu page
  function my_add_submenu_pages() {
    add_submenu_page( 'my-plugin', __( 'All Players', 'Players' ), __( 'All Players', 'Players' ), 'manage_options', 'my_plugin_show_posts', 'my_render' );
    add_submenu_page( 'my-plugin', __( 'Add New Player', 'Players' ), __( 'Add New Player', 'Players' ), 'manage_options', 'my_plugin_add_post', 'my_render_new' );
   
  }
  
  // These two functions insert a redirect to the 
  // custom post type pages
  function my_render(){
    $url = admin_url().'edit.php?post_type=player_profile';
    ?>
     <script>location.href='<?php echo $url;?>';</script>
    <?php
  }
   
  function my_render_new(){
    $url = admin_url().'post-new.php?post_type=player_profile';
    ?>
    <script>location.href='<?php echo $url;?>';</script>
    <?php
  }
   
  
  // Remove the post type menu from the main navigation
  add_action( 'admin_menu', 'my_remove_cpt_menu_items' );
   
  function my_remove_cpt_menu_items() {
    remove_menu_page( 'edit.php?post_type=player_profile' );
  }


  // This javascript ensures the proper menu is
  // highlighted on the left-hand side after our redirect.
  function my_correct_current_menu(){
    $screen = get_current_screen();
    if ( $screen->id == 'player_profile' || $screen->id == 'edit-player_profile' ) {
    ?>
	    <script type="text/javascript">
	    jQuery(document).ready(function($) {
	      $('#toplevel_page_my-club-manager').addClass('wp-has-current-submenu wp-menu-open menu-top menu-top-first').removeClass('wp-not-current-submenu');
	      $('#toplevel_page_my-club-manager > a').addClass('wp-has-current-submenu').removeClass('wp-not-current-submenu');
	    });
	    </script>
    <?php
    }
   
    if ( $screen->id == 'player_profile' ) {
    ?>
	    <script type="text/javascript">
	    jQuery(document).ready(function($) {
	      $('a[href$="my_plugin_add_post"]').parent().addClass('current');
	      $('a[href$="my_plugin_add_post"]').addClass('current');
	    });
	    </script>
    <?php
    }
   
    if ( $screen->id == 'edit-player_profile' ) {
    ?>
	    <script type="text/javascript">
	    jQuery(document).ready(function($) {
	      $('a[href$="my_plugin_show_posts"]').parent().addClass('current');
	      $('a[href$="my_plugin_show_posts"]').addClass('current');
	    });
	    </script>
    <?php
    }
  }
   
  add_action('admin_head', 'my_correct_current_menu', 50);

  ?>
© Evan Smith 2009 - 2017