WordPress comes with many useful functions developers can make use of in their plugins. Today we’ll look at the URL manipulation functions – add_query_arg
and remove_query_arg
, both part of WordPress core.
add_query_arg
Incredibly useful in plugin development, add_query_arg
lets you reliably modify an existing URL by adding or changing it’s query arguments. So for example, if you want to append a query var named ‘page’ set to ‘2’ to the current URL, you could use:
add_query_arg( 'page', 2 );
It’s that easy – you don’t need to worry about the existing query string, or ‘?
‘ And ‘&
‘ characters as it’s all handled for you.
The function can be used in two ways:
For adding a single argument
In its simplest form, add_query_arg
will let you pass a name, value, and optionally an $old_query_or_uri
you wish to append the arguments to.
add_query_arg( $key, $value, $old_query_or_uri );
For adding multiple arguments
To add multiple arguments at once you only need add an array, and again optionally the $old_query_or_uri
.
add_query_arg( array( $key1 => $value, $key2 => $value ), $old_query_or_uri );
In practice, let’s say we want to add some ordering arguments to a page in admin. We could use this:
add_query_arg( array( 'order' => 'asc', 'orderby' => 'title' ), admin_url( 'admin.php?page=myplugin' ) );
This would give us:
http://yoursite.com/wp-admin/admin.php?page=myplugin&order=asc&orderby=title
remove_query_arg
This function will remove single or multiple query arguments from a URL you define, or the current URL. To remove a single argument, pass a string:
// current url: http://yoursite.com/?order=asc&orderby=title
echo remove_query_arg( 'order' );
// echos: http://yoursite.com/?orderby=title
To remove multiple arguments, pass an array of string:
// current url: http://yoursite.com/?order=asc&orderby=title
echo remove_query_arg( array( 'order', 'orderby' ) );
// echos: http://yoursite.com/
Important: Don’t forget to escape!
This caught me out a few weeks ago when I found out (the hard way) that WordPress doesn’t automatically sanitize the current URL if you don’t pass in your own. You need to use esc_url
during output:
echo esc_url( add_query_arg( $key, $value ) );
If you forget to do this, a malicious URL, for example one containing some JavaScript, could potentially be output and executed on your page. Escape all the things to be safe!
Comments
One response to “Use WordPress’ URL manipulation functions”
How could you improve on the result and have pretty URLs such as page/2 instead of ?page=2 ?