Skip to content

How-to Guides

Technical References

Code Quality and Best Practices /

Encode values passed to add_query_arg

Add_query_arg() is a really useful function, but it might not work as you thought it did.

If one does:

$my_url = 'admin.php?action=delete&post_id=321';
$my_url = add_query_arg( 'my_arg', 'somevalue&post_id=123', $my_url );

You would expect the url to be: admin.php?action=delete&post_id=321&somevalue%26post_id%3D123
But in fact it becomes: admin.php?action=delete&post_id=321&somevalue&post_id=123

Your URL has now been hijacked and you will be deleting post 123 instead of 321.

To protect against this use rawurlencode() so that

"somevalue&post_id=123"

get converted into

"somevalue%26post_id%3D123"

Which is now safe.

You can either convert every single argument:

add_query_arg( 'my_arg', rawurlencode( 'somevalue&post_id=123' ), $myurl );

Or update all your arguments at once:

$args = array(
	'my_arg' => 'somevalue&post_id=123',
	'my_second_arg' => $my_second_arg;
);
$args = array_map( 'rawurlencode', $args );
$my_url = add_query_arg( $args, $my_url);

Last updated: November 19, 2020