How to pass extra variables in your WordPress website URL?

If you are a WordPress developer, many a times a situation arises where you need to pass extra variables in you WordPress website url. Even after digging google deep enough you will not find a appropriate solution for this. I am providing you a best way to add and receive extra variables in WordPress website url. There is a function for this in WordPress add_query_arg()

/* where 9 is the post id or page id */
add_query_arg( 'hello', 'there', get_permalink( 9 ) );

Now if you want to add variables to a page a want to reload it with new page or send to a different page after adding these variables then you can use the wp_safe_redirect(), have a look at the code below.

$urltoaddargs = get_permalink(); // you can also add your own custom url here.
wp_safe_redirect( add_query_arg( array( 'key' => 'value' ), $urltoaddargs) );

You can also use the esc_url() function to create your own url. have a look at the code below.

// use of esc_url to echo url with args.
 echo esc_url( add_query_arg( 'key', 'value' ) );

Feel free to comment below your doubt or suggestions about the code above.

Authored By :

I am a Sr. Web Developer passionate about blogging and teaching. When I am not coding or writing blogs, I prefer traveling (Which I like most). I am also doing a bit or research on Indian Startups now a days.


Leave a Reply

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