Wordpress: How can I add url GET parameter to my main menu items

前端 未结 4 371
醉话见心
醉话见心 2021-01-12 17:25

I\'m trying to add a URL GET parameter to one of my main menu items in Wordpress(but I don\'t know how to). So, my approach was to detect a click event on the menu item, the

相关标签:
4条回答
  • 2021-01-12 17:58

    That's a fork from Brasofilo that works perfectly for me: (Put this code on your theme functions.php)

    // Transform title attributes to parameters
    add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );
    function nav_items( $items, $menu, $args )
    {
        if( is_admin() )
            return $items;
        foreach( $items as $item )
        {
        if ($item->attr_title != "") $item->url .= '#' . $item->attr_title;
        }
        return $items;
    }
    

    What I'm doing here is to get the attributes of the menu-item and transform them to an anchor name. This way I will have this type of URL's: www.domain.com/my-page#anchor1

    After this I just need to do some jQuery magic to jump (progressive scroll down) to the anchor. (Codepen).

    If you cannot see the 'Title Attribute' input field just be sure to check the options on the top "Screen Options" button of Wordpress Admin menu...

    0 讨论(0)
  • 2021-01-12 18:02

    I would suggest to use custom menus in Appearance>Menus. It will help you to retain custom URLs with get parameters. You may read it here Wordpress Menu

    0 讨论(0)
  • 2021-01-12 18:21

    The problem is that you are attempting to pass a boolean value in your Ajax call with the variable homeclick. GET requests simply use text because the data is passed thru the URL, so if you are wanting a logical/boolean type you can use either "true" and "false" in text or perhaps 0 and 1. Also you have a syntax error, see below.

    Try the following:

    In you ajax call, fix the syntax as well as set homeclick to "true" as follows: data: ({ homeclick: 'true' }),.

    And in your php, change the if condition for variable $homeclick as follows: $homeclick == 'true'.

    You may want to consider using a POST method if you want to utilize a boolean.

    0 讨论(0)
  • 2021-01-12 18:24

    The filter hook wp_get_nav_menu_items is used to manipulate the Nav Menus. The post_title used in the example is the title of the Menu (Navigation Label), not of the post/page.

    home nav menu

    Drop this code in your functions.php file, adjust the post_title and ?my_var=test to your needs. Note that better than functions is to create your own plugin.

    add_filter( 'wp_get_nav_menu_items','nav_items', 11, 3 );
    
    function nav_items( $items, $menu, $args ) 
    {
        if( is_admin() )
            return $items;
    
        foreach( $items as $item ) 
        {
            if( 'Home' == $item->post_title)
                $item->url .= '?my_var=test';
    
        }
        return $items;
    }
    
    0 讨论(0)
提交回复
热议问题