WordPress Add javascript:void(0); to menu link item?

I want to add javascript:void(0); to menu link item instead of # but it is not accepting any JavaScript.
Now i am thing to replace # with javascript:void(0); using filters, but could not find the appropriate filter for the task.

Can any one tell me which filter can be used for this task.

Note. I know this could be done with javascript/jQuery but this is for SEO purposes so have to do it with PHP on server side and render the correct html for google Spider, to avoid duplicate URL issue.

2 Answers
2

I am not sure how it does effect the SEO but just to answer this
question:-

You can not save menu item with javascript:void(0); because WordPress filter the URL using function esc_url() thus removing bad values. And it all happens in Nav Walker class. So you need to alter the URL when WordPress done with filtering and returning final safe HTML.

You can use filter walker_nav_menu_start_el if your theme does not have custom nav menu walker class OR does have this filter in walker class.

Example:-

add_filter('walker_nav_menu_start_el', 'wpse_226884_replace_hash', 999);
/**
 * Replace # with js
 * @param string $menu_item item HTML
 * @return string item HTML
 */
function wpse_226884_replace_hash($menu_item) {
    if (strpos($menu_item, 'href="#"') !== false) {
        $menu_item = str_replace('href="#"', 'href="javascript:void(0);"', $menu_item);
    }
    return $menu_item;
}

Leave a Comment