• Hi
    When someone enters the site with a query string (for example /?utm_source=google), I need to make some changes like change the phone and forms.
    I managed to do that somehow, but now I also need the query string to pass along to all pages the user navigates to. So if the user clicks the menu and moves on to another page I need to add the query string to the url so it will look like m/some-page?utm_source=google
    I started by at least trying to rewrite the url with some fixed query string but it doesn’t work.

    This is the code I added to functions.php:

    
    function custom_rewrite_basic() {
    	add_rewrite_rule('.*', add_query_arg( 'key', 'myValue' ,$_SERVER['REQUEST_URI']));
    }
    add_action('init', 'custom_rewrite_basic');
    
    • This topic was modified 7 years, 5 months ago by oritc.
    • This topic was modified 7 years, 5 months ago by Jan Dembowski.

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

Viewing 3 replies - 1 through 3 (of 3 total)
  • Either you’ll have to filter or your output and add this query string to all internal links, which can be quite a task. You need to change all links in the navigation and any links you may have put in widgets, in your content or in your theme files themselves…
    If you go this way, remember that the rewrite would be different if there already are some query variable in the URL.

    Perhaps a nicer solution would be to set a variable and also throw the user a session cookie? Then you can set the variable IF the query string is there OR if that cookie was received.

    Thread Starter oritc

    (@oritc)

    I know I will have to use a session cookie (that will be the next thing I do). But as a start, I just tried to rewrite the url to see if the rewrite works for me and it doesn’t…

    Moderator bcworkz

    (@bcworkz)

    You wouldn’t use WP rewrite rules to alter outgoing links (or whatever it is you’re trying to do, I’m not sure). Rewrite rules are for interpreting permalinks and converting elements to query args that are used to handle the current request. As the incoming data already is in a query arg, there would be no point. The rewrite API doesn’t even “see” query args, only the permalink itself.

    What you need is code that detects the particular query arg in a request (in the $_REQUEST array) and then sets a session cookie accordingly. This can go in plugin code or theme functions.php. It doesn’t even need to be in a hook callback, it can execute immediately as long as no WP functions are used, since WP is not yet stable. If you need WP functions, hook “init” action.

    Then the template code that outputs conditional content only needs to check for the presence of the session cookie since the cookie is set well before template code executes.

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

The topic ‘rewrite url with arguments’ is closed to new replies.