返回 WordPress 中的当前 URL

问题描述 投票:0回答:4

我正在尝试在 WordPress 中实现规范和 hreflang 标签,但我无法检索访问页面的当前 URL。

我试过了:

 <?php echo site_url(); ?>

但它返回

https://www.example.com
而不是
https://www.example.com/current-page1

php wordpress url return-value
4个回答
8
投票

以防其他人需要这个。下面的代码应该获取包含参数的确切 URL。

home_url($_SERVER['REQUEST_URI']);

您可以根据您的用例回显或返回它。 例如

echo home_url($_SERVER['REQUEST_URI']);

return home_url($_SERVER['REQUEST_URI']);

7
投票

site_url()
函数返回实际的网站根URL。根据您调用 URL 的位置,您可以尝试
get_the_permalink()
,但更可靠的方法是使用
$wp->request
方法。像这样:

global $wp;
echo home_url( $wp->request )

此函数的主要问题是省略了 URL 参数,因此如果您的链接类似于:

http://example.com/test/?myparam=1
,它只会返回
http://example.com/test/


2
投票

这是我的两分钱。所描述的方法使用

$_SERVER
全局,而不验证每个查询变量的完整性。

即使未注册的变量/值对不属于 WordPress 公共查询环境

WP_Query
类(由
WP_Query
识别),也会显示。

我建议在返回当前永久链接之前将每个查询变量与公共查询变量范围进行比较。

<?php

/**
 * Safely retrieve the current permalink.
 *
 * @param String $args['relative'] (true|false), Relative path if true. Default to false. 
 *
 * @return String Relative or absolute path to the current permalink.
 * 
 * @since 1.0.0
 *
 * @see https://stackoverflow.com/a/70809779/3645650
 */
function wpso_50761584( $args = array( 'relative' => false ) ) {
        
    global $wp;

    // Parse the current query string into variables
    parse_str( $_SERVER['QUERY_STRING'], $variables );

    // Filter out unregistered query variables
    $filtered_vars = array_filter( $variables, function ( $value, $variable ) {

        return get_query_var( $variable );
        
    }, ARRAY_FILTER_USE_BOTH );

    // Rebuild the URL with the filtered query variables
    $permalink = add_query_arg( $filtered_vars, home_url( $wp->request ) );

    // Make the URL relative if requested
    if ( $args['relative'] ) {

        $permalink = wp_make_link_relative( $permalink );

    };

    return esc_url_raw( $permalink );

}

举个例子,你可以在前端回显它:

<?php

echo wpso_50761584( 
    array(
        'relative' => true
    )
);

1
投票

如果永久链接设置为普通链接:

$actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
© www.soinside.com 2019 - 2024. All rights reserved.