Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In WordPress, get current URL including query string
<?php
/**
Re-use some existing WordPress functions so you don't have to write a bunch of raw PHP to check for SSL, port numbers, etc
Place in your functions.php (or re-use in a plugin)
If you absolutely don't need or want any query string, use home_url(add_query_arg(array(),$wp->request));
Hat tip to:
+ http://kovshenin.com/2012/current-url-in-wordpress/
+ http://stephenharris.info/how-to-get-the-current-url-in-wordpress/
*/
/**
* Build the entire current page URL (incl query strings) and output it
* Useful for social media plugins and other times you need the full page URL
* Also can be used outside The Loop, unlike the_permalink
*
* @returns the URL in PHP (so echo it if it must be output in the template)
* Also see the_current_page_url() syntax that echoes it
*/
if ( ! function_exists( 'get_current_page_url' ) ) {
function get_current_page_url() {
global $wp;
return add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp->request ) );
}
}
/*
* Shorthand for echo get_current_page_url();
* @returns echo'd string
*/
if ( ! function_exists( 'the_current_page_url' ) ) {
function the_current_page_url() {
echo get_current_page_url();
}
}
?>
@ovidiubica

This comment has been minimized.

Copy link

ovidiubica commented Sep 8, 2014

Any idea how to add a slash before the query string?

@ovidiubica

This comment has been minimized.

Copy link

ovidiubica commented Sep 8, 2014

Nevermind, 'trailingslashit' is the answer. Thanks a lot for the function.

@widoz

This comment has been minimized.

Copy link

widoz commented May 27, 2015

Thank you for the snippet, it work like a charm

@janw-me

This comment has been minimized.

Copy link

janw-me commented Feb 9, 2016

This one is shorter:

echo home_url( add_query_arg( null, null ));
@dima-stefantsov

This comment has been minimized.

Copy link

dima-stefantsov commented Mar 22, 2016

Thanks janw-oostendorp !

@tarpanpatel

This comment has been minimized.

Copy link

tarpanpatel commented Apr 19, 2016

Best answer

@jonaslundman

This comment has been minimized.

Copy link

jonaslundman commented Jun 29, 2017

Am I the only one that missing something or
echo home_url( add_query_arg( null, null ));
Does not work as intended, on subdomains the subdomain get repeated.
add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp->request ) )
Last slash get missing, might corrupt endpoints url:s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.