Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

The add_query_arg() Helper Function

Posted on August 12, 2012 by Pippin in Functions, Intermediate, Tutorials 2 Comments
Home» Functions » The add_query_arg() Helper Function
Tweet
Love It - 2

WordPress includes a lot of helper functions that can make your life as a developer much easier. One function in particular that I really love is add_query_arg(), which provides an extremely simply way to append query variables to any URL. Query vars, in case you’re not familiar with them, allow you to perform any number of tasks based on the information passed through the URL.

The add_query_arg() function accepts three parameters:

  • name – the argument name
  • value – the value of the argument in the first parameter
  • URL – the URL to append the argument to. This defaults to the current URL

Let’s say, for example, that you want to create a button that redirects to a URL like this:

http://yoursite.com/?view=list

The view variable can be used, for example, to modify your template layout, and so you might also have this:

http://yoursite.com/?view=grid

It is pretty easy to create your URL like this:

<?php echo home_url('?view=list'); ?>

But if you are dealing with more complex URL structures, especialy URLs that are not always the same, perhaps because they contain other query variables, this does not work reliably. And this is where add_query_arg() comes in.

The example below will render the exact same thing as the example above with home_url(), but it will be much more flexible (I’ll show you why in a moment):

<?php echo add_query_arg( 'view', 'list', home_url() ); ?>

The result of this will be:

http://yoursite.com/?view=list

The question you should ask now is “why should I use add_query_arg() instead of just adding ?view=list to my URL?”. The answer is simple: add_query_arg() allows you to append a query arg to any existing URL without disturbing existing variables AND it will ensure that the resulting URL has proper trailing slashes (or doesn’t). Take the following URL as an example:

http://yoursite.com/?something=value&second-var=this-value

Imagine that is the URL you are working with and you need to now append the “view=list” argument. First of all, the following will fail:

http://yoursite.com/?something=value&second-var=this-value?view=list

It will fail because only the very first argument starts with a ?, all others are separated with an &, so this puts you in a situation where you need to do some checking to figure out whether you need to use “?view=list” or “&view=list”. Checks like that, while not terribly difficult, do require a couple of conditional checks. Why do that when you can simply do the following?

1
2
3
4
5
6
7
<?php 
echo add_query_arg(
	'view',
	'list',
	'http://yoursite.com/?something=value&second-var=this-value'
);
?>

The add_query_arg() function will take care of adding our new argument with either ? or &. This means that the following will also work:

1
2
3
4
5
6
7
<?php 
echo add_query_arg(
	'view',
	'list',
	home_url()
);
?>

And let’s say that you don’t necessarily know what the URL is, or perhaps you just want to append the arguments to the current URL, no matter what it is. You can do this:

1
2
3
4
5
6
<?php 
echo add_query_arg(
	'view',
	'list'
);
?>

By leaving out the third parameter, WordPress will simply append your arguments to whatever the current URL is, including any existing query variables.

Adding Multi Query Arguments

Often times you will need to add multiple variables to your URL, and add_query_arg() makes this extremely simple. The first two parameters can be replaced with an associative array of key to value pairs. Like this:

1
2
3
4
5
6
7
8
9
<?php
echo add_query_arg(
	array(
		'var_key' => 'key_value',
		'another_var' => 'My Value'
	),
	home_url()
);
?>

This will result in a URL like this:

http://yoursite.com/?var_key=key_value&another_var=My%20Value

Note that add_query_arg() takes care of URL encoding the values through the use of urlencode_deep() automatically, so there is no need to encode the values yourself.

Tweet Follow @pippinsplugins
add_query_arg

2 comments on “The add_query_arg() Helper Function”

  1. Gijs says:
    August 12, 2012 at 4:07 pm

    Hi Pippin,

    Very, very useful. Needed this before and built it myself, because I didn’t know this helper existed.
    Thanks!

    Gijs

    Reply
  2. Syamil MJ says:
    August 12, 2012 at 4:16 pm

    For added security, especially for dynamically generated URLs, use esc_url e.g.

    echo esc_url(add_query_arg(
    	array(
    		'var_key' => $some_var,
    		'another_var' => $some_var2
    	),
    	home_url()
    ));
    
    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • User Submitted Image Gallery – Part 5

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • RT @Astoundify: We are hiring p/t tech support rep for our support forum if your interested email contact [at] http://t.co/bcXNhcwZx5
    May 23, 2013
  • @trepmal @Namecheap I&#039;ve double refunded my certs there three times. Stupid
    May 23, 2013
  • @digitalFocus I&#039;m done for the day but can chat tomorrow
    May 23, 2013

Topics

hook meta box Rémi Corson featured shortcodes campaign monitor add_options_page register_setting Sugar Event Calendar attachments add_shortcode wp_enqueue_script the_content image forms short codes Related posts login do_action authors mail chimp attachment plugin recent posts comments post types bbpress apply_filters short code taxonomies custom post type Ajax images gallery Stripe jquery taxonomy users widgets add_filter easy content types add_action widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins