I’m looking for a way to create a new item that can be added to a menu.
Here are the details of my problem: I use WPML. WPML have that nice feature that you can add the switcher to a menu, automatically. It adds it at the end of the menu, no control on that.
Thing is, I want my language switcher to be element 4 out of 6. That feature to automatically add the element at the end doesn’t fit my needs.
So I want to create a new element that can be used in apparence->menu to put my language switcher exactly at the spot I want it.
Is there any way to do that?
TLDR: I want to be able to push custom HTML/PHP code in a menu element (Apparence->Menu). Any functions to do so?
From
wp-includes/nav-menu-template.php
, inWalker_Nav_Menu::start_el
:Which means you can append to individual nav menu item HTML contents (right before the last
li
tag) using that filter.$item_output
contains the HTML generated for the item so far. Example:That would append
<span>hello world</span>
to each nav menu item HTML. A closingli
tag will be appended after this filter. You can use the 4th argument ($args
) to validate the currently rendering navigation menu.All right, I have temporary solution.
These are steps:
wp-contentpluginssitepress-multilingual-cmsinclanguage-switcher.php
function wp_nav_menu_items_filter($items, $args){
Add this right after first
{
:Right before
if ( $abs_menu_id == $settings_menu_id || false === $abs_menu_id ) {
add this:Go to bottom of function and before:
}
return $items;
Add:
}}
Now, before
return $items;
Add:If you get stuck here is how that whole function looks for me:
I will try to make it easier to change where you want to place widget.
Comment if you have problems. Good luck!
Edit: Explanation what this modified function does.
This function is used to add language switcher to menu.
When this function is called, we have
$items
string containing all menu items.I transferred all menu items from
$items
to$tempitems
and set$items
to empty string.Why? Because now we can insert widget as first menu item or between some menu items.
Then we explode that
$tempitems
string so we could use another order.When you now specify
$id
this becomes our offset.And now in first loop, with help of
$id
, we add some temp items to empty$items
string, and then language widget and at the end remaining menu items.You can create a new template even if you’re using a pre-developed
theme
ortemplate
.Just copy the code from the template you want to use and modify it accordingly on your
localhost
and upload the modified copy to the theme directory.Make sure you keep a copy in case you update the theme to a newer version because it’ll be overwritten.
Another option would be to develop a child theme.