0

When displaying in the sidebar the menu containing the list of posts, this menu also displays the link to the current post (the current page)

How avoid the link of the current post in this list of posts ?

The files actually used are wp-content/themes/mytheme/sidebar.php, wp-includes/nav-menu-template.php and wp-includes/nav-menu.php.

I use the Navigation Menu Widget.

2
  • 1
    which widget do you use to display the menu ?
    – mmm
    Mar 29, 2018 at 16:20
  • Please see th e details I added to my question
    – hedgehog
    Mar 30, 2018 at 7:17

1 Answer 1

1

you can try this code. the first filter is to customise the widget arguments and the second filter is in the menu generation.

add_filter("widget_nav_menu_args", function ($nav_menu_args, $nav_menu, $args, $widget_instance) {

    $post = get_queried_object();

    if (is_a($post, "WP_Post")) {
        $nav_menu_args["remove_post_in_widget"] = $post->ID;
    }


    return $nav_menu_args;

}, 10, 4);


add_filter("wp_nav_menu_objects", function ($sorted_menu_items, $args) {

    if (isset($args->remove_post_in_widget)) {

        foreach ($sorted_menu_items as $index => $item) {

            if ((int) $item->object_id === $args->remove_post_in_widget) {
                unset($sorted_menu_items[$index]);
                break; // stop the loop when the first post is found
            }

        }

    }


    return $sorted_menu_items;

}, 10, 2);
2
  • I start with this software. despite my experience in php I have never used hooks. Can I add this code as is in the widget page? In the widget's code I have the line: wp_nav_menu (apply_filters ('widget_nav_menu_args', $ nav_menu_args, $ nav_menu, $ args, $ instance)); Should I touch this line too? In the navigation menu code, I have the same questions for the second code snippet
    – hedgehog
    Apr 3, 2018 at 16:31
  • you should not edit the core file of wordpress because your changes will be lost on the next update. to use this hooks, you have to create a new plugin : codex.wordpress.org/Writing_a_Plugin
    – mmm
    Apr 5, 2018 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.