Are you building a WordPress theme or creating custom features for your WordPress site? Knowing how to retrieve the wordpress get current url of a page or post can be really handy, regardless of what you’re working on. In this simple guide, I’ll show you how to get the current URL using PHP in WordPress.
Get Current Page URL Using PHP
This small piece of PHP code will help you fetch the current page’s URL from any type of WordPress page on your website. Whether it’s a single post, a page, an archive, or a category, this code snippet will work for capturing the URL of any page on your site.
<?php global $wp; $current_url = home_url( add_query_arg( array(), $wp->request ) ); echo $current_url;
There are many other ways to also obtain the current URL in WordPress.
Get Current WordPress Slug Using PHP
If you only need the slug of the current page or post, you can use this PHP function. It will work for different types of pages in WordPress, like archive pages or single posts.
<?php global $wp; $current_slug = add_query_arg( array(), $wp->request ); echo $current_slug;
The WordPress slug is like the name of a page after your website’s address. For instance, in “yoursite.com/contact/”, the slug is “about”. It helps identify content in a clear and unique way.
Get Current Page URL with Query String using PHP
If you’d like the complete web address of your page along with the extra information like ?page=2 after it, you can utilize the following piece of code.
The query string often looks something like ?page=2 attached to your URL. If you intend to use query variables in your PHP functions, you can employ WordPress’ get_query_var() function.
<?php $url_parts = parse_url( home_url() ); $current_url_with_query_string = $url_parts['scheme'] . "://" . $url_parts['host'] . add_query_arg( NULL, NULL ); echo $current_url_with_query_string;
Do you have more questions about working with WordPress? Feel free to ask them in the comments section below.
Related Articles
Leave a Reply