• Hello guys

    I need to create navigation item with custom URL: domain.com/food-menu/?menu-date=2021-05-03

    But date should change automatically based on current date (variable).

    for example: domain.com/food-menu/?menu-date={current-date}

    How can I achieve this ? Thanks for help`

    The page I need help with: [log in to see the link]

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    It depends on what navigation item you want to affect. If you mean the WP nav menu, there are a number of filters you could use to alter URLs dynamically. For example, “wp_nav_menu” filter passes the entire menu HTML to your callback. You can insert whatever arbitrary HTML you wish into the passed HTML using PHP string manipulation such as str_replace().

    There are other filters that pass item objects or individual items. Or you could invoke a custom walker class to completely alter the menu’s HTML structure if you wanted to.

    If it’s not a WP nav menu that you need to alter, there are likely similar hooks available for your use if WP functions are involved. However, for links that do not come from WP functions, what is possible to do is highly variable. It all depends on how the link came to be in the first place.

    Thread Starter samuelmarcinko

    (@samuelmarcinko)

    I found a code on stackoverflow and edited it little bit.

    add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );
    
    function nav_items( $items, $menu, $args ) 
    {
       
        foreach( $items as $item ) 
        {
            if( 'Order' == $item->post_title)
                $item->url .= "?menu-date=" . date("Y-m-d") . "";
    
        }
        return $items;
    }

    it looks that is working fine, but I have a problem. If I change nav item label from Order to 2 words for example ( if( ‘Order Food’ == $item->post_title) ) then is a date in URL duplicated like here:

    /denne-menu/?menu-date=2021-05-04?menu-date=2021-05-04

    How can I fix that ?

    Moderator bcworkz

    (@bcworkz)

    I think your concatenation code is OK. What’s happening is the hook is firing more than once per request. To ensure your code only runs once per request, use remove_filter() at the end of your callback function to remove itself from the filter stack.

    Most people don’t realize a lot of hooks do this because typical filter code does no harm by running multiple times.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Today’s date in URL’ is closed to new replies.