When you don’t know if query string was started or not you can use add_query_arg
which it knows how to deal with that and adds the “?
” or “&
” marks (which ever one is needed) to the query string.
Update
By popular demand I’m adding a few examples that are from the codex:
Using get_permalink:
Since get_permalink() returns a full
URL, you could use that when you want
to add variables to a post’s page.
// This would output whatever the URL to post ID 9 is, with 'hello=there' appended with either ? or &, depending on what's needed
echo add_query_arg( 'hello', 'there', get_permalink(9) );
more general:
Assuming we’re at the WordPress URL
"http://blog.example.com/client/?s=word"...
// This would output '/client/?s=word&foo=bar'
echo add_query_arg( 'foo', 'bar' );
// This would output '/client/?s=word&foo=bar&baz=tiny'
$arr_params = array ( 'foo' => 'bar', 'baz' => 'tiny' );
echo add_query_arg( $arr_params );
Or for use with any link you have you can pass the link uri:
//say your link is: http://wordpress.stackexchange.com/questions/14827/
//then use:
echo add_query_arg( 'hello', 'world','http://wordpress.stackexchange.com/questions/14827/');
to get http://wordpress.stackexchange.com/questions/14827/?hello=world
Example plugin page URL with extra query args:
$query_args = array( 'page' => 'your-plugin-page', 'foo' => 'bar' );
echo add_query_arg( $query_args, admin_url( '/options-general.php' ) )
// outputs
// http://example.com/wp-admin/options-general.php?page=your-plugin-page&foo=bar