• vahost

    (@vahost)


    I occasionally need to pass a parameter via my permalinks’ URLs, and when I do so, I capture that parameter in a session variable: $_SESSION[‘myparam’].

    Once my $_SESSION variable gets populated, I need my primary navigation menu to temporarily rewrite all the URLs of each menu item in that menu with ?myparam=X at the end of each URL.

    However, I DON’T want this to be a permanent change. I only want it to apply to the current session.

    For example, a primary menu item that points to: https://www.example.com/page/ needs to temporarily point to: https://www.example.com/page/?myparam=X instead for the duration of the session.

    Is there a way to accomplish this without permanently rewriting the URLs of the primary menu items?

Viewing 3 replies - 1 through 3 (of 3 total)
  • RossMitchell

    (@rossmitchell)

    This probably can be done using a filter. The filter would examine the status of the session (are you logged in etc), and if necessary modify the menu entries.

    There is a list of available filters in the online documentation.

    Thread Starter vahost

    (@vahost)

    Well, my first attempt at writing a WordPress filter isn’t going so well. I’ve been piecing this together based on various tutorials I’ve seen around the web, but it doesn’t actually do anything when I try to apply it in my test WordPress site.

    Here’s what I have so far.

    /* Add myparam parameter to all primary menu items */
    function revise_menu_urls ( $args ) {
        $menu_name = 'primary';
        $menu = wp_get_nav_menu_object( $locations[ $menu_name ] );
        $menu_items = wp_get_nav_menu_items($menu->term_id);
        $menu_items = new WP_Query( apply_filters( 'revise_menu_urls_filter', $menu_items ) ) ;
        if ( $_SESSION['myparam'] ) {
            foreach ( (array) $menu_items as $key => $menu_item ) {
                $menu_item->url = $menu_item->url . '?myparam=' . $_SESSION['myparam'];
            }
        }
        return apply_filters( 'revise_menu_urls', $menu_items );
    }
    add_filter ( 'revise_menu_urls_filter' , 'revise_menu_urls' );

    Unfortunately, the menu items don’t get modified with the addition of my myparam parameter.

    Can someone please show me where I went wrong and what the correct code should be?

    RossMitchell

    (@rossmitchell)

    The filter mechanism works on text, the text that is being output to your web browser. I see that you are manipulating menu data structures, this has to be on the wrong track.

    Suggest that you peruse this mammoth list of actions and filters:
    https://adambrown.info/p/wp_hooks/hook

    Then find an example of someone using that filter.
    At a guess start with: wp_get_nav_menu_items

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Temporarily modify urls of primary nav menu programmatically’ is closed to new replies.