最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to override url params with rewrite rules vars?

programmeradmin0浏览0评论

Setup a rule:

add_action( 'init',  function() {
    add_rewrite_rule( '^myparamname/?$', 'index.php?myparamname=hello', 'top' );
} );

Whitelist the query param:

add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'myparamname';
    return $query_vars;
} );

Get query vars:

localhost/myparamname

get_query_var('myparamname'); // hello

localhost/myparamname?myparamname=hi or localhost/myparamname/?myparamname=hi

get_query_var('myparamname'); // hi

As you can see, "hi" message is displayed instead of "hello" in the second example. Here, the desired situation is generally "hello".

Setup a rule:

add_action( 'init',  function() {
    add_rewrite_rule( '^myparamname/?$', 'index.php?myparamname=hello', 'top' );
} );

Whitelist the query param:

add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'myparamname';
    return $query_vars;
} );

Get query vars:

localhost/myparamname

get_query_var('myparamname'); // hello

localhost/myparamname?myparamname=hi or localhost/myparamname/?myparamname=hi

get_query_var('myparamname'); // hi

As you can see, "hi" message is displayed instead of "hello" in the second example. Here, the desired situation is generally "hello".

Share Improve this question asked Jan 9, 2021 at 19:50 l6lsl6ls 3311 gold badge3 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

"hi" message is displayed instead of "hello" in the second example

Yes, because that's how it works: query_vars is a hook for registering custom query vars that are public, so if the URL query string contains the custom query var, then WordPress will set the query var to the value parsed from the query string.

the desired situation is generally "hello"

You can override the query var via the request hook. E.g.

add_filter( 'request', function ( $query_vars ) {
    if ( isset( $query_vars['myparamname'] ) ) {
        $query_vars['myparamname'] = 'hello';
    }

    return $query_vars;
} );

Just be sure to use a unique query var or be cautious that you don't override query var that shouldn't be overridden.

发布评论

评论列表(0)

  1. 暂无评论