Skip to content

Instantly share code, notes, and snippets.

@jserrao
Created April 18, 2018 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jserrao/28f4447bf711d559e32455550614e6e7 to your computer and use it in GitHub Desktop.
Save jserrao/28f4447bf711d559e32455550614e6e7 to your computer and use it in GitHub Desktop.
A JS <a> and <li> switcher for WordPress menus
/* MAIN MENU ITEM SWITCH
*
* Description:
* For whatever reason, it's near impossible to get the WP markup in the menu to switch around
* So we're begrudgingly doing it in JS
* This is accomplished by using a regex that breaks the capture after each list item end tag
*
* Usage:
* Really simple - just pass in the class / ID for the sidebar menu container
* This function is not really reusable due to the regex but encapsulation is a good idea in a big JS file
*
* Params:
* sidebarContainer - the ID/class of the sidebar menu container (jQuery selector, please include # or .)
*
*/
function menuItemSwitch(sidebarContainer) {
// 1- Get entire content of sidebar menu ul, then split by row
var listItems = $(sidebarContainer).html();
var listItemsArray = listItems.match(/(.*<\/li>)/gm);
// 2- Set up variables
var listItemsTemp = [];
var listItemsRearranged = new Array(listItemsArray.length);
var listItemsRearrangedConcat = new Array(listItemsArray.length);
// 3- Take listItemsArray and loop through it w/ regex
for (var i = 0; i < listItemsArray.length; i++) {
// 4- Use regex to break each list item into five pieces
listItemsTemp[i] = listItemsArray[i].match(/(<li\b(?:>\s+(?:id="([^"]*)"|class="([^"]*)")|[^\s>]+|\s+)*>)|((<\w+\b>)|(<a\shref=".*">)|(.+?(?=<))|(<\/\w+\b)>)/g);
// 5- Setup listItemsRearranged[i] with an array of listItemsTemp.length
listItemsRearranged[i] = new Array(listItemsTemp.length);
// 6- Take listItemsTemp and reassign positions
// We can do this because our string will always have five pieces
listItemsRearranged[i][0] = listItemsTemp[i][1];
listItemsRearranged[i][1] = listItemsTemp[i][0];
listItemsRearranged[i][2] = listItemsTemp[i][2];
listItemsRearranged[i][3] = listItemsTemp[i][4];
listItemsRearranged[i][4] = listItemsTemp[i][3];
// 7- Join the array back into a string
listItemsRearrangedConcat[i] = listItemsRearranged[i].join("");
}
// 8- Finally, we rejoin the string and print back into the page
var listItemsFinal = listItemsRearrangedConcat.join("");
$(sidebarContainer).html(listItemsFinal);
}
menuItemSwitch(".sidebar-nav");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment