-1

I am trying to add a new menu item to an already existing nav menu in my theme, I am using some part of this answer How to Hard Code Custom menu items

I am directly using this code in my plugin

wp_update_nav_menu_item(2, 0, array(
    'menu-item-title' =>  __('Home'),
    'menu-item-classes' => 'home',
    'menu-item-url' => home_url( '/' ), 
    'menu-item-status' => 'publish'));

But it gives me following error

Your PHP code changes were rolled back due to an error on line 357 of file C:\xampp\htdocs\wordpress\wp-includes\link-template.php. Please fix and try saving again

Call to a member function get_page_permastruct() on null

3
  • never edit you code from the wordpress "code editor" Commented Apr 2, 2018 at 10:40
  • @MarkKaplun Why ? , and where should i edit it then
    – beginner
    Commented Apr 2, 2018 at 10:45
  • Why? because it is extremely insecure practice, and it is easy to make an edit that will break your site without an ability to remove it. Use a proper editor, with an integrated FTP support, or an FTP software that can detect local changes and upload to the server "automagically" Commented Apr 2, 2018 at 12:32

2 Answers 2

0

adding it to 'init' action hook works

function update_menu_custom(){
wp_update_nav_menu_item(2, 0, array(
    'menu-item-title' =>  __('Home'),
    'menu-item-classes' => 'home',
    'menu-item-url' => home_url( '/' ), 
    'menu-item-status' => 'publish'));
}

add_action('init','update_menu_custom');

But it still doesn't works as expected, It adds too many menu items with name home, But that is a different issue

1
  • register_activation_hook Commented Jul 23, 2018 at 11:03
0

The wp_update_nav_menu_item should be used with register_activation_hook with the following instructions. In your functions.php of your plugin or theme or any other php that it is always executed add:

register_activation_hook(__FILE__,'addnav_menu_init');


function addnav_menu_init(){
     wp_update_nav_menu_item(2, 0, array(
    'menu-item-title' =>  __('Home'),
    'menu-item-classes' => 'home',
    'menu-item-url' => home_url( '/' ), 
    'menu-item-status' => 'publish'));
}

THEN DEACTIVATE AND REACTIVATE THE THEME OR THE PLUGIN in order to add this page to menu, otherwise it does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.