Passing variables via URL to WordPress Posts and Pages

Passing variables via URL to WordPress Posts and Pages

I was asked today if I knew of a way to pass a string to WordPress – specifically to add a variable to an Aweber form.

The main reason we want to pass a variable to an AWeber form is so we can capture an Affiliate name or ID for later tracking etc.  I’ve used this method previously on html and php files, but not with WordPress – so I went to find out.

Essentially, what we wanted to do was have a url formatted as follows:

http://thewpwarrior.com/wordpress/616/passing-variables-via-url/?refid=Charly

The word ‘Charly’ would then be used to populate one of the hidden fields in my AWeber form.

My investigations led me to a post by Webopius, discussing custom URL paramaters in WordPress – which has proved incredibly helpful.

From this post, I took three steps to implement the functionality.

Part 1 – Add a new URL paramater to WordPress

I first added the following code to my functions.php file for my theme:

add_filter('query_vars', 'parameter_queryvars' );

function parameter_queryvars( $qvars )
{
$qvars[] = 'refid';
return $qvars;
}

(A note to say that this code is placed within the <?php and ?> tags in fuctions.php)

This specific code adds a single new URL parameter name ‘refid’ to WordPress.

Part 2 – Add A Function To Retrieve And Display The URL Paramater

The next part is to actually be able to get the passed variable from the URL and then display where ever you want.

I decided to implement this part as a function within my theme because I knew it was something that I would want to do many times and it’s neater to call a function, than duplicate the code multiple times.

In fuctions.php, I added:

function echorefid()
{
global $wp_query;
if (isset($wp_query->query_vars['refid']))
{
print $wp_query->query_vars['refid'];
}
}

(Remember, this code goes in between the <?php and ?> tags)

Step 3 – Display The Passed Variable In My AWeber Form Hidden Field

This part can be replicated for anything really – not just displaying the variable in the AWeber Form Hidden Field.  However, I’m going to share how I added the passed variable to my AWeber form….

To be able to achieve this, we have to use the AWeber HTML code (not the javascript code).  Once you’ve created your AWeber Form and you are at the ‘publish your form’ stage, click on the Raw HTML Version tab and copy the code that appears in there.

In the post or page you want to display your form, go to the HTML tab (not visual editor) and paste the code where you want the form to appear. (Please note, that there is a bit of work required when using the new formatted forms from AWeber, which is not covered here).

Once you’ve pasted the HTML, locate the line that looks like:

<input type="hidden" name="meta_adtracking" value="">

If  that line doesn’t exist, add it between other lines in the form code…

Modify the line to look like:

<input type="hidden" name="meta_adtracking" value="<?php echorefid();?>">

The code:
<?php echorefid();?>

calls the function echorefid() (that you added to your functions.php file) and displays the value for refid that is passed in the URL.

  • http://www.productlaunchconsultancy.com David Walsh – Product Launch C

    Thanks Charly,

    Much much appreciated. I’ll be putting it to good use right now! ;)

    David

    .-= David Walsh – Product Launch Consultant´s last blog ..Product Launch System =-.

  • http://www.productlaunchconsultancy.com David Walsh – Product Launch Consultant

    Thanks Charly,

    Much much appreciated. I’ll be putting it to good use right now! ;)

    David

    .-= David Walsh – Product Launch Consultant´s last blog ..Product Launch System =-.

  • http://askcharlyleetham.com Charly Leetham

    You’re most welcome – would love to see your final product when it is done.

    Charly.

  • http://askcharlyleetham.com Charly Leetham

    You’re most welcome – would love to see your final product when it is done.

    Charly.

  • http://sales-expert.co.uk Al

    Hi,

    This looks great. Couple of quick questions:

    1. Can you use this to substitute a word contained in the URL the actual post?

    For example, if the sentence below is part of a post, I would like to substitute the “variable1″ for the word contained in the dynamic part of the URL.

    Post template: “My favourite animal is [variable1]”
    URL: mydomain.com?variable1=dog
    Result: “My favourite animal is dog”

    I have looked at cookie monster plugin which seems to do the job, but conflicts with my theme and WP Chameleon which is equally excellent in principle but I cannot get the [shortcode] to work.

    2. If we can do this, does it need my post to execute PHP? If so, how would I do this and avoid someone from executing php in the comments?

    I really appreciate any advice or guidance you can provide!

    Al

  • http://sales-expert.co.uk Al

    Hi,

    This looks great. Couple of quick questions:

    1. Can you use this to substitute a word contained in the URL the actual post?

    For example, if the sentence below is part of a post, I would like to substitute the “variable1″ for the word contained in the dynamic part of the URL.

    Post template: “My favourite animal is [variable1]”
    URL: mydomain.com?variable1=dog
    Result: “My favourite animal is dog”

    I have looked at cookie monster plugin which seems to do the job, but conflicts with my theme and WP Chameleon which is equally excellent in principle but I cannot get the [shortcode] to work.

    2. If we can do this, does it need my post to execute PHP? If so, how would I do this and avoid someone from executing php in the comments?

    I really appreciate any advice or guidance you can provide!

    Al

  • admin

    Hi Al

    To do this you just have to subsitute ‘refid’ for ‘variable1′ in the php code. So you would have:

    add_filter(‘query_vars’, ‘parameter_queryvars’ );

    function parameter_queryvars( $qvars )
    {
    $qvars[] = ‘variable1′;
    return $qvars;
    }

    function echovariable1()
    {
    global $wp_query;
    if (isset($wp_query->query_vars['variable1']))
    {
    print $wp_query->query_vars['variable1'];
    }
    }

    and to display ‘variable1′ you would have

    < ?php echovariable1();?>

    and yes your post would need to execute PHP. If you use the plugin Exec-PHP then php won’t execute in comments.

  • Mike

    I’ve been using this method too but I don’t fully understand how it works. Suppose I want to add more than one variable that can be passed by URL. Do I have to write more than one plugin? How can I add adapt this plugin code to make wordpress recognize more than one variable?

  • Mike

    I’ve been using this method too but I don’t fully understand how it works. Suppose I want to add more than one variable that can be passed by URL. Do I have to write more than one plugin? How can I add adapt this plugin code to make wordpress recognize more than one variable?

  • http://askcharlyleetham.com Charly Leetham

    Hi Mike,

    To be able to pass and use more variables, this should work:

    Let’s assume you use the following url:
    http://thewordpresswarrior.com/616/passing-variables-via-url/?refid=Charly&campaign=89&source=twitter

    The variables being passed in are:
    refid, campaign and source

    Part 1 – Add the new URL paramaters to WordPress

    The code in functions.php would look like:

    add_filter(‘query_vars’, ‘parameter_queryvars’ );

    function parameter_queryvars( $qvars )
    {
    $qvars[] = ‘refid’;
    $qvars[] = ‘campaign’;
    $qvars[] = ‘source’;
    return $qvars;
    }

    $qvars is an array of URL parameters

    To use the variables, you would then do someting like:

    $query_vars['refid'].”;
    echo ‘Campaign is: ‘.$wp_query->$query_vars['campaign'].”;
    echo ‘Source is: ‘.$wp_query->$query_vars['source'].”;
    ?>

    The output would be:
    Referrer is: Charly
    Campaign is: 89
    Source is: twitter

    So to pass more variables in the URL, add the extra parameters to the parameter_queryvars function.

    Cheers,
    Charly.
    .-= Charly Leetham´s last blog ..WebHosting: What Every Business Owner Should Consider =-.

  • http://askcharlyleetham.com Charly Leetham

    Hi Mike,

    To be able to pass and use more variables, this should work:

    Let’s assume you use the following url:
    http://thewordpresswarrior.com/616/passing-variables-via-url/?refid=Charly&campaign=89&source=twitter

    The variables being passed in are:
    refid, campaign and source

    Part 1 – Add the new URL paramaters to WordPress

    The code in functions.php would look like:

    add_filter(‘query_vars’, ‘parameter_queryvars’ );

    function parameter_queryvars( $qvars )
    {
    $qvars[] = ‘refid’;
    $qvars[] = ‘campaign’;
    $qvars[] = ‘source’;
    return $qvars;
    }

    $qvars is an array of URL parameters

    To use the variables, you would then do someting like:

    < ?php
    global $wp_query;
    echo 'Referrer is: '.$wp_query->$query_vars['refid'].’
    ‘;
    echo ‘Campaign is: ‘.$wp_query->$query_vars['campaign'].’
    ‘;
    echo ‘Source is: ‘.$wp_query->$query_vars['source'].’
    ‘;
    ?>

    The output would be:
    Referrer is: Charly
    Campaign is: 89
    Source is: twitter

    So to pass more variables in the URL, add the extra parameters to the parameter_queryvars function.

    Cheers,
    Charly.
    .-= Charly Leetham´s last blog ..WebHosting: What Every Business Owner Should Consider =-.

  • http://Beshoy.Girgis.US Beshoy Girgis

    Hello,

    I’m wondering if it’s possible to put this PHP in a page or post — the “Edit Page” feature in wordpress’ admin panel.

    When I put PHP code in the html tab, nothing prints to the screen where the variable should be.

  • http://Beshoy.Girgis.US Beshoy Girgis

    Hello,

    I’m wondering if it’s possible to put this PHP in a page or post — the “Edit Page” feature in wordpress’ admin panel.

    When I put PHP code in the html tab, nothing prints to the screen where the variable should be.

  • http://www.presscoders.com David Gwyer

    Hi Charly,

    Thanks, just what I was looking for! Will be able to complete the first version of my Simple Sitemap plugin now. :)

    David

  • http://www.presscoders.com David Gwyer

    Hi Charly,

    Thanks, just what I was looking for! Will be able to complete the first version of my Simple Sitemap plugin now. :)

    David

  • AliMH

    Really thank you, i really need this for my site.

  • Judy

    This works for me on normal pages/posts – how might i do it with admin pages? I tried same procedure, but it is not getting picked up…

  • http://askcharlyleetham.com Charly Leetham

    Hi Judy,

    The code is only meant for the front end functionality. The admin panels are different and this method wouldn’t work (as you discovered). Not sure on what you’re trying to achieve with the admin panels, so it’s hard to ‘point you in the right direction’.

  • Geno

    how to i use the variable in a custom sql query?

    $query=”SELECT * FROM wp_table where field=echoteam() ORDER BY field DESC”;

  • Dennis

    Hi Charly! This is exactly what I’ve been looking for, but I can’t seem to get it to work. I know there must be something really simple that I’m overlooking. When I test my form, in my AWeber account, in the Ad Tracking value column, I’m seeing the literal value .

    To me, it seems as if I’m missing a step… that functions.php is not running… and I’m such a WP nube, I don’t know how to test that.

    On another note, I want to take this one step further… I want to take the form fields that are entered and URL pass them to another page outside of WordPress. I need to give them specific variable names in order for them to pre-pop in the next page.

    I tried putting code like this right in the text widget where I’m pasting my AWeber form code:

    $fname = $_REQUEST['awf_first'] ;
    $lname = $_REQUEST['awf_last'] ;
    $email = $_REQUEST['email'] ;

    … and then in the hidden redirect URL, appending like this:

    http://www.example.com/?refid=“”>&fname=$fname&lname=$lname&email=$email……

    Of course, that didn’t work.

    SO, is there something I need to do to make functions.php work with the text widget where I’m pasting my form?

    And, can you give me some direction on how to solve the second problem?

  • Dennis

    Of course, at the end of the first paragraph, I was trying to say…

    I’m seeing the literal value <?php echorefid();?>

    And, later in the post, I was trying to say…

    … and then in the hidden redirect URL, appending like this:

    http://www.example.com/?refid=
    <?php echorefid();?> “>&fname=$fname&lname=$lname&email=$email……

  • http://askcharlyleetham.com Charly Leetham

    Hi Dennis,

    I’m not sure I really understand your question….

    functions.php is a file that forms part of your wordpress theme. You can typically edit this by going to wp-admin -> appearance -> editor and you’ll see a list of the theme files…

    However, it sounds like you are trying to execute php in your posts – by default, WordPress strips all the PHP tags out. You need to use a plugin like Exec-PHP to ensure your handcoded php is executed in posts and pages.

    http://wordpress.org/extend/plugins/exec-php/

    Highly recommend that you proceed with caution. Editing your functions.php file incorrectly can stop your website from working.

    C

  • Dennis

    Thanks Charly! I installed the ExecPHP plugin and now the solution you present above works to pull the URL passed “refid” and pass it to my AWeber meta_adtracking.

    Now, I want to to grab the form values that the user inputs and pass them to the redirect URL as well. Would I follow an approach similar to what you explain to Mike below? Would that change make it so that onSubmit, the user input values could be added to the redirect URL?

    (No worries about the edits to functions.php. I have already gotten the WSOD on more than on occasion, and I just access the site via FTP and reverse the last change that I made. Besides, I’m just trying to get all this functionality set up before launch, so if I had to completely re-install, it wouldn’t present a problem… IOW, not working on a “live” site.)

  • http://twitter.com/erikbriones erik briones

     this worked for me ;) thank you for making this tutorial! ;)

  • http://www.facebook.com/jovannih Jovanni Hernandez

    I’m not sure I quite understand the array structure. What in that structure would I go about modifying to pass more than one variable? Thanks!

  • Rajm12m

    Can u tell me what is query_var and and its uses…………….plz tell bcz now i am totally confused …

  • Kevin

    I tried this as-is, and in the Ad Tracking field I just end up with the actual text:
    Any Ideas what I may have done wrong? 

  • Kevin

    I tried this as-is, and in the Ad Tracking field I just end up with the actual text:

    (I added spaces to the text above, first comment didn’t take it – security no doubt, hopefully this works…
    Any Ideas what I may have done wrong?

  • http://askcharlyleetham.com Charly Leetham

    Hi Kevin,

    To process php code within your posts and pages you need to be using a plugin that allows that to happen.  As standard, WordPress will not process php code.  I use the EXEC PHP plugin.  I suspect this is the issue.

    Of course, the other thing is to ensure that you are entering the form code through the HTML editor and not the visual editor (which I’m sure you are).

    Without seeing exactly how you’re doing this, it’s difficult to tell what’s going on – but that’s normally the issue.

    Charly.

  • Kevin

    Hi Charly

    Thank
    you for your feedback, and that was exactly the issue. I ended up
    finding that out, after some head-scratching wondering why the PHP code
    wasn’t executing in a Text widget – so – searched for plugins – and it
    started working.However, strangely – the
    function did not return what I needed it to do – I put the code in my
    themes function.php – and, no success…However – I did find a way to get it to work, simplifying it (without the need of anything in functions.php).My input field just ended up as this:< input type="hidden" name="meta_adtracking" value=" ” />Without any use of the function, and it works just fine when a URL parameter is used.Thanks again for your response / reply!

    Kevin

  • Charles Olivier

    Hi Charly

    This does not work for me. (I am using pretty permalinks.)

    What I want to do, is the following:

    The site’s home page, let’s say http://www.whatever.com, makes use of a template file with static info that is not index.php (where the blog items appear).

    I want to pass a variable to the home page, let’s say source=banana. Then I want to include the source variable with value of banana into a hidden field in my own form on the home page.

    How do I pass the variable to be captured by the home page? I would like to use something like http://www.whatever.com/source/banana. Is this possible?

    Regards
    Charles

  • Cesar Mejia

    Thank you so much! I’ve dealing with this for 48 straight hours..actually just in case anyone would bump into something like this: I needed to pass variables, but TO a page or POST, not just to a template, which I did like charming using this same approach but in a plugin… if you need to pass vars to a POST or PAGE this is it!

  • Farnau74

    I have try this for several query_vars. What is wrong?

    add_filter(‘query_vars’, ‘parameter_queryvars’ ); function parameter_queryvars( $qvars ) { $qvars[] = array(‘taxloc’,'taxdis’,'taxacu’,'taxibp’); return $qvars; }

  • http://askcharlyleetham.com Charly Leetham

    Hi Farnau74,

    you need to modify your code as follows:
    add_filter(‘query_vars’, ‘parameter_queryvars’ );

    function
    parameter_queryvars( $qvars ) {
    $qvars[] = ‘taxloc’;
    $qvars[] = ‘taxdis’;
    $qvars[] = ‘taxacu’;
    $qvars[] = ‘taxibp’;
    return $qvars;
    }

    Your function:
    $qvars[] = array(‘taxloc’,'taxdis’,'taxacu’,'taxibp’);

    Is actually creating a multidimensional array.

    Cheers

  • Farnau74

    Thank you for your answer!! ;)

  • http://askcharlyleetham.com Charly Leetham

    Hi Charles,

    Using a url of something like: http://www.whatever.com/source/banana  and pass the ‘variable’ of banana to another function is certainly possible, but it’s relatively complex.

  • http://askcharlyleetham.com Charly Leetham

    Hi Kevin,

    A few things come to mind:
    1. you need to have a plugin like EXEC PHP enabled on your site.
    2. Make sure you edit that part of the code in the html editor (not visual editor) because the <? will be translated to text otherwise and not executed when the page loads.

  • Casey Stanton

    Having a bit of trouble here – I just want to display a few variables on a WordPress that I can easily do in a static PHP page:
    Hey Your date is

    If my url is example.com/?fname=Bob&date=1/2/2013 I can get this to echo easily with a basic PHP page. Any ideas what I can do to get it working with WordPress?

    Thanks for your help!

  • Nrogers

    Hi
    this seems the ticket , but unfortunately I still have permissions problems.
    WP Vers = 3.3.1  so (apparently)  I have to use Admin.php as opposed to functions.php (of which there are 3 (one is deprecated in favour of admin.php, and then 2 others, one each in themes twentyeleven and another in twentyten).
    However, none of them make a difference. I still get the Insufficient Permissions error screen, when trying to postback to my form (for an edit operation on a row in a grid) with 2 query parameters.eg
         localhost/wordpress/wp-admin/admin.php?page=my-submenu-handle3?Action=Edit&recId=1

    I put the following code in
        function parameter_queryvars( $qvars )    {        $qvars[] = ‘Action’;        $qvars[] = ‘recId’;        return $qvars;    }

Powered by WishList Member - Membership Site Software