I'm pretty new to Drupal 8. I'm trying to figure out how to programmatically add a query string to a menu item link, the specific query string is determined by the node/page the user is currently on.

For example, I've got a link on my primary menu that goes to http://www.example.com

If I'm on the 'about me' page I want the link to add a query string of '?origin=about'. (http://www.example.com?origin=about)

If I'm on the 'contact me' page I want the link to add '?origin=contact', etc.

Are there any modules where this can be done, or how might I go about doing this myself?

  • what's the purpose of having the ?origin=about part?
    – No Sssweat
    Commented Feb 11, 2017 at 0:49
  • These links go to another site, which wants to track the origin of the traffic.
    – Joel
    Commented Feb 13, 2017 at 16:43

1 Answer 1


The menu is cached. You could disable caching and add the query string to the options of the url in hook_link_alter, but this is not good for performance. So this would be better solved in javascript. You can prepare the link in php by setting an attribute, so that you can easily find the link later in the client and attach the query string.

  • OK I've got it working, just want to check if I did it the 'right' way. I set up a field in my content types 'field_optional_query_string'. In _page_attachments_alter I'm getting the current node, checking to see if it has the field, and then adding it to drupalSettings. On the js side I'm grabbing the drupalSetting and appending it to the menu item via jquery.
    – Joel
    Commented Feb 13, 2017 at 23:43

Your Answer

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

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