I've been working on a solution but my logic isn't quite there yet.
I'm looking to insert string A at multiple positions (positions from an array) into string B.
The array of positions variable is a strpos() return value[].
String B must be concatenated with itself so it contains the original string but with the new string A inserted at in multiple places.
Here's the logic so far:
function add_submenu_back_item( $items, $args ){
if( 'top-menu' == $args->theme_location ){
$menu_item_back = '<a ><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z"/>
</svg></a>';
$subMenuPos = strpos($items, 'sub-menu');
$new_items = '';
$arrayPos = strpos_all( $items, 'sub-menu' );
$offset = 10;
$values;
for ($i = 0; $i <= count($arrayPos) - 1; $i ) {
// $new_items = substr_replace($items, $menu_item_back, $arrayPos[$i] $offset, 0);
echo substr_replace($items, $menu_item_back, $arrayPos[$i] $offset, 0);
}
}
return ''; // testing mode, should be $new_items but doesnt seem to output the inserted value
}
add_filter( 'wp_nav_menu_items', 'add_submenu_back_item', 10, 2 );
What I think the logic should express:
- substr() Get the current startPos and endPos to cut out of the string.
- Add the insert value to the end of substr() value.
- if we already have a substr() value then add the new substr() with the insert value to the last one.
- repeat this logic until for loop ends.
I'm trying to insert the $menu_item_back into $menu_items. $items is a string representing HTML menu navigation.
At the moment it's returning a repeated list $menu_items.
CodePudding user response:
I decided to use JavaScript for this solution. It was easier to access the DOM elements as needed and is a better way to solve this solution since it's Frontend dev and not server-side dev.
Code:
// create go-back element button
var goBackEl = document.createElement('li');
goBackEl.innerHTML = '<a href="#"><svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="#FFFFFF" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M12 8a.5.5 0 0 1-.5.5H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5a.5.5 0 0 1 .5.5z"/></svg></a>';
// add go-back button to sub-menu as the first child
submenuEl.prepend( goBackEl );