Blog / WordPress/ Standard Methods to Get the Current Page URL in WordPress

Standard Methods to Get the Current Page URL in WordPress

WordPress 获取当前页面完整 URL 的几种标准方法

Introduction

When developing WordPress themes or plugins, you often need to retrieve the full URL of the currently accessed page. This article outlines several reliable, standard methods and explains their appropriate use cases.

Method 1: Using WordPress Core Functions

This is the most recommended approach. It leverages WordPress core functions, correctly handling the site's permalink structure, SSL status, and query parameters.

global $wp;
$current_url = home_url( $wp->request );
// To include query strings:
$current_url_with_query = home_url( add_query_arg( array(), $wp->request ) );

Explanation: $wp->request contains the path portion of the current request (excluding domain and query string). The home_url() function automatically prepends the protocol and domain, handling HTTPS correctly.

Method 2: Using home_url with Server Variables

This method also uses WordPress functions but directly appends the request URI from server variables, ensuring the full path including query strings is captured.

$current_url = home_url( $_SERVER['REQUEST_URI'] );

Note: This is a simple and effective method. home_url() ensures the base URL is correct.

Method 3: Custom Function (For Non-WordPress or Fine Control)

Here is a robust custom function that builds the URL by analyzing the $_SERVER superglobal, accounting for HTTPS, port numbers, and other details. Useful in pure PHP projects or when deep customization is needed.

<?php
/**
 * Get the full URL of the current page.
 *
 * @return string The current page's full URL.
 */
function get_current_page_url() {
    $protocol = ( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ) ? 'https://' : 'http://';
    $host = $_SERVER['HTTP_HOST'];
    $request_uri = $_SERVER['REQUEST_URI'];
    return $protocol . $host . $request_uri;
}
?>

Usage:

<?php echo get_current_page_url(); ?>

Important: In a WordPress environment, Method 1 is strongly preferred. It integrates deeply with WordPress routing and configuration, making it the most reliable and maintainable option. Use a custom function only for specific edge cases.

Summary and Best Practices

  • Standard Practice: In WordPress themes or plugins, always use home_url( $wp->request ) or home_url( $_SERVER['REQUEST_URI'] ).
  • Security: The URLs returned by these methods are safe to output directly.
  • Performance: Using WordPress core functions typically offers better performance and compatibility with caching plugins.

Avoid outdated or overly complex custom code snippets. Following the core API makes your code more robust and future-proof.

Post a Comment

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