Search code examples
wordpressads

adding a custom post type as a sub-menu of another existing page menu


I added a page menu in admin panel via this code and it works fine.

add_menu_page('Ads Dashboard', 'Ads Dashboard', 'administrator', 'adverts', 'advert_admin_options');

And now I need to add/register post type under this menu, but it doesn't work properly. Seems something is wrong in my code here is my whole code for both:

function add_ads_post_type(){ 
    register_post_type('ads', array(
        'labels' => array(
            'name' => __('Adverts', 'theme'),
            'singular_name' => __('Adverts', 'theme'),
            'menu_name' => __('Adverts', 'theme'),
            'add_new' => __('Add Advert Item', 'theme'),
            'add_new_item' => __('Add New Advert item', 'theme'),
            'edit_item' => __('Edit Advert item', 'theme'),
            'new_item' => __('New Advert item', 'theme'),
            'view_item' => __('View Advert item', 'theme'),
            'search_items' => __('Search Advert items', 'theme'),
            'not_found' => __('No Advert found', 'theme'),
            'not_found_in_trash' => __('No Advert items found in Trash', 'theme'),
        ),
    'public' => TRUE,
        'rewrite' => array('slug' => 'ads', 'with_front' => false),
        'has_archive' => true,
        'supports' => array('title', 'editor'),
        'show_in_menu' => 'admin.php?page=adverts'
    )); 
}
function advert_add_to_menu() {
    if (is_admin()) {
        add_menu_page('Ads Dashboard', 'Ads Dashboard', 'administrator', 'adverts', 'advert_admin_options');
        add_submenu_page('adverts', 'Ads', 'Ads', 10, 'ads-list', 'add_ads_post_type' );
    }
}
add_action('admin_menu', 'advert_add_to_menu');

Solution

  • try this : post type is 'ads'

    //REMOVE MENU
    
    
    function remove_menu_CPT_ads() {  
            remove_menu_page( 'edit.php?post_type=ads' );  
    }
    add_action( 'admin_menu', 'remove_menu_CPT_ads' );
    function add_my_menu(){
     add_submenu_page('adverts', 'Ads', 'Ads', 'manage_options', 'my-top-level-slug','Your_function');
    }
     add_action('admin_menu','add_my_menu');
     function Your_function(){   
         wp_redirect(admin_url().'/edit.php?post_type=ads');
         exit;
     }
     function add_ob_start(){
        if(is_admin()){
         ob_start();
        }
     }
     add_action('admin_init', 'add_ob_start');