Generate Advanced Custom Fields box in custom admin menu page

Interesting exercise, a one page plugin that believes it deserves a first level menu page is wrong, IMO. I use the same technique with Jetpack.

To create sub-pages in the Options Page add-on, read the documentation.

The logic of this menu/sub-menu swapping is:

  1. Add multiple ACF Options Pages
  2. Create our menu first level page
  3. Remove (hide) our plugin page
  4. Add (move) our plugin page into ACF’s

Steps 1 and 2 are to make this example generic.
To use it with any other plugin, only steps 3 and 4 are necessary, adjusting the slugs.
To move it into a default WP menu, for example, use add_theme_page (Appearance) or add_options_page (Settings).

<?php
/**
 * Plugin Name: Swap Menus and Sub-menus
 * Plugin URI: http://wordpress.stackexchange.com/q/95981/12615
 * Author: brasofilo
 * Author URI: http://wordpress.stackexchange.com/users/12615/brasofilo
 * Licence: GPLv2 or later
 */

class Swap_Menus_WPSE_95981 {

    function __construct()
    {
        add_action( 'plugins_loaded', array( $this, 'modify_menus' ) );
    }

    function modify_menus() 
    {
        // 1) Add ACF Options pages
        if( function_exists( "register_options_page" ) )
        {
            register_options_page( 'Header' );
            register_options_page( 'Footer' );
        }

        // 2) Create this plugin page
        add_action( 'admin_menu', array( $this, 'add_aux_menu' ) );

        // 3) Remove (hide) this plugin page
        add_action( 'admin_init', array( $this, 'remove_aux_menu' ) );

        // 4) Move this plugin page into ACF Options page
        // Priority here (9999) is to put the submenu at last postition
        // If the priority is removed, the submenu is put at first position
        add_action( 'admin_menu', array( $this, 'add_aux_menu_again'), 9999 );
    }

    function add_aux_menu() 
    {
        add_menu_page(
            'Dummy Page First Level', 
            'Dummy Title', 
            'edit_posts', 
            'dummy-page-slug', 
            array( $this, 'menu_page_content' )
        );
    }

    function menu_page_content() 
    {
        ?>
            <div id="icon-post" class="icon32"></div>
            <h2>Dummy Page</h2>
            <p> Lorem ipsum</p>
        <?php
    }

    function remove_aux_menu() 
    {
        remove_menu_page( 'dummy-page-slug' ); 
    }


    function add_aux_menu_again() 
    {
        // To move into default pages, f.ex., use add_theme_page or add_options_page
        add_submenu_page(
            'acf-options-header', // <---- Destination menu slug
            'Dummy Page Second Level', 
            'Dummy Page Second Level', 
            'edit_posts', 
            'dummy-page-slug', 
            array( $this, 'menu_page_content' )
        );
    }
}

new Swap_Menus_WPSE_95981();

Leave a Comment