I’m using wp_insert_post()
to add a new page in WordPress. This inserts the post into wp_posts
which in turn makes the post show up in the Dashboard.
From there, I have to manually click and drag under the Pages tab to make that post a menu item in my nav bar,
How can I do this from the PHP side? I’ve scanned the Codex and can’t find what I’m looking for. There doesn’t seem to be a WordPress function for that sort of thing.
Problem solved.
While WordPress provides no specific function for adding items and sub-items to the nav bar, there’s a workaround. The project involved an author being able to add new books to her database, and have them automatically show up in the nav bar as a sub-item under “Books” without having to go through the Dashboard to do it.
I went to
header.php
in the theme dir and found thewp_nav_menu()
function. After reading this article, I was able to modify the output, usingstr_replace
to add some<li>
tags of my own.This is what the default looked like:
Here’s my modified version:
What I did next was basically call up the links (called “guid” in the table) and post titles from “wp_posts” table in the WordPress database. I also needed to get the book names from my own “books” table. The book titles are the same as the “post_title” in “wp_posts”.
Now comes the part that had me stumped. You can add arguments to the
wp_nav_menu
function by adding them into the array inside. The important ones I needed were the “theme_location” and “echo”. I put all of this in a variable:Setting “echo” to false makes the HTML of the function an editable PHP variable. Now we can manipulate it much more easily:
And finally:
That’s my end of the work. Every time she adds a new book, my plugin uses
wp_post_insert()
to add the page to “wp_posts” and adds the book to my “books” table. From there, this script should add that new book to the top of her navigation page 🙂