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”.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0