Insert code when users come from an specific referer

Your post does make sense, you just want to change/add some content based on referrer, which is very common among websites.

Now, as you asked just at the start of body. I don’t believe there is any standard hook in there, other than get_header();. This function is usually located at the very beginning of most of the template files.

The common structure of a single post is something like this:

<?php get_header(); ?>

    // Some content
<?php get_sidebar(); // If your theme has a sidebar ?>

<?php get_footer(); ?>

So you should be able to hook into this and output your content. This goes into your theme’s functions.php or a plugin:

add_action('get_header', 'my_referrer_check');
function my_referrer_check () {
    $referer = wp_get_referer();
    if (  strpos($referer ,'http://wanteddomain.com') !== false ){
        // The rest of your code here
    }
}

This will automatically add your code to the get_header action hook.

The other solution is to wrap your code in a function and use that function inside your template, wherever you wish:

function my_referrer_check () {
    $referer = wp_get_referer();
    if (  strpos($referer ,'http://wanteddomain.com') !== false ){
        // The rest of your code here
    }
}

Now by using my_referrer_check(); you can get your content anywhere.

Some handy functions

In the path of conquering your adventure, you might need some allies. These functions might serve you well, at the time of needs:

  • To redirect a user : wp_redirect('URL-HERE'); or
    wp_safe_redirect('URL-HERE'); followed instantly by a die(); or
    exit();
  • To check whether you are on a single post or any where else on your
    templates: is_single(), is_page(), is_home(), etc.
  • To get the query parameters: get_query_var('paremeter-here');

Leave a Comment