Search code examples
javascriptphp.htaccessurl-rewritingdrupal-6

Using PHP or JavaScript, can I append some text to every href URL rendered in a page?


first time posting! I'll try to be as clear as possible.

I have a Drupal 6 website and am using a custom template file to render some pages differently than the rest of the website.

This is what the code I'm working with looks like:

<?php print $header; ?> 
<?php if ($title): ?><h1><?php print $title; ?></h1><?php endif; ?>
<?php print $content ?>

The page renders correctly when the URL looks like this: http://example.com/somepage/?format=kiosk

Except any link that is rendered in the page will go to: http://example.com/otherpage/

What I need dynamically appended to the end of any URL is:

?format=kiosk

Is there a to process these links using PHP or JavaScript, without resorting to .htaccess (though that's an option), to add that bit to the URL?

I suppose this could also be handy for other things, like Google Analytics.

Thanks!

Jon


Solution

  • Here is a solution using jQuery which runs a quick regex check to make sure the anchor tag is a link to a page on http://example.com. It also checks to see if the link already has a ? or not.

    var $links = $('a'); // get all anchor tags
    
    // loop through each anchor tag
    $.each($links, function(index, item){
        var url = $(this).attr('href'); // var for value of href attribute
        // check if url is undefined
        if(typeof url != 'undefined') {
            // make sure url does not already have a ?
            if(url.indexOf('?') < 0) {
                // use regex to match your domain
                var pattern = new RegExp(/(example.com\/)(.*)/i);
                if(pattern.test(url))
                    $(this).attr('href', url + '?format=kiosk'); // append ?format=kiosk if url contains your domain
            }
        }
    });