Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect from add_menu_page

Tags:

wordpress

I have added a menu using add_menu_page which all works correctly, but when clicked I want this menu page to open the post editor for a particular post id.

As a proof of concept i have tried echoing a javascript redirect out into the do function like so...

// Load up the menu page
 function register_availability_custom_menu_page() {
   add_menu_page('custom menu title', 'Availability', 'add_users', 'options',             'options_do_page');
}

function options_do_page() {
echo "<script type=\"text/javascript\">";
echo "window.location = '/whatever_page.php';";
echo "</script>";
}

This approach does work but I was wondering if it is the best approach, is there a better way to redirect to the page I am after?

UPDATE

I have now also tried using wp_redirect with this code...

add_action( 'admin_menu' , 'admin_menu_new_items' );

function admin_menu_new_items() {
    wp_redirect( home_url() );
    exit;
}

This gives me a Headers already sent error, can anyone suggest where I am going wrong?

like image 576
fightstarr20 Avatar asked Nov 03 '22 20:11

fightstarr20


1 Answers

If I'm understanding this correctly, you don't need the redirect. Instead of using a $menu_slug in the function add_menu_page, put the address of the target page, e.g.:

$the_post_title = 'The Portfolio';

add_action( 'admin_menu', 'wpse_59050_add_menu' );

function wpse_59050_add_menu() 
{
    global $the_post_title;
    $our_page = get_page_by_title( $the_post_title );

    $settings_page = add_menu_page( 
        'Edit '.$our_page->post_title, 
        'Edit '.$our_page->post_title, 
        'add_users', 
        '/post.php?post='.$our_page->ID.'&action=edit', 
        '', 
        '', 
        2
    );
}

This function is from the following WordPress Answer: Highlighting a Menu Item by Post Name. You'll need some jQuery to do the correct highlighting of this top level menu, check both my and TheDeadMedic answers in that Q.

This other one is useful too: Add highlighting to new Admin Dashboard Menu Item.

like image 116
brasofilo Avatar answered Nov 08 '22 03:11

brasofilo