I am trying to remove the query string from my URLs when I redirect them but it is preserving them. I can’t get the regex right.
Also, I have multiple templates that redirect to different urls so I can’t just use .*
after howto.php
.htaccess
is not an option in this case so I must figure out how to do this in the Redirection plugin
I want /templates/howto.php?page=template-business-plan
to go to
/business-plan
but i keep getting /business-plan?page=template-business-plan
I also use this plugin, so I figured I’d dig into the code to see if I can find the answer.
There are two actions you could use for this that may work redirection_first and redirection_last
Both take two arguments: $url and $this (which is the wordpress module for the redirection plugin)
Here’s the snippet of code from the module init() in \modules\wordpress.php
public function init() {
$url = $_SERVER['REQUEST_URI'];
// Make sure we don't try and redirect something essential
if ( ! $this->protected_url( $url ) && $this->matched === false ) {
do_action( 'redirection_first', $url, $this );
$redirects = Red_Item::get_for_url( $url, 'wp' );
foreach ( (array) $redirects as $item ) {
if ( $item->matches( $url ) ) {
$this->matched = $item;
break;
}
}
do_action( 'redirection_last', $url, $this );
}
}
So, $url is your requested URL, and in redirection_last, $this->matched has your redirection url in it. I would start with redirection_start and you could run something like:
function redirection_strip_query_string( $url="", $this ) {
if ( strpos( $url, '?page=" ) !== false ) {
$url = preg_replace("/\?.*/', '', $url);
}
}
add_action( 'redirection_first', 'redirection_strip_query_string' );
Two notes:
- I have not tested this code.
- I wanted to give credit to the simple URL preg_replace