It doesn’t work with add_rewrite_rule()
because of the ?view=
part in the URL (it’s the first parameter for the function) — i.e. WordPress strips that query string part, hence it’s not included when WordPress finds a matching rewrite rule.
how I can remove
?view=12a34b56
after set post name
You can’t (not on the same page), because that is a query string in the request URL which PHP reads from upon loading the page, and the browser already “put” the URL in the address bar.
But because I believe you want a 301 (permanent) redirect whereby the URL in the browser’s address bar changes, then you can easily achieve that redirect via the parse_request
hook — you could also use the init
hook, but with parse_request
, WordPress already parses the request path (e.g. https://example.com/this-path/
), so we can simply read from the parsed data, i.e. the $wp->request
below.
So this should work for you, but make sure to remove that pre_get_posts
code from your file:
add_action( 'parse_request', 'wpse_375940' );
function wpse_375940( $wp ) {
if ( 'book.php' === $wp->request &&
! empty( $_GET['view'] )
) {
$query = new WP_Query( [
'name' => $_GET['view'],
'fields' => 'ids',
] );
if ( ! empty( $query->posts ) &&
$url = get_permalink( $query->posts[0] )
) {
// Or use 302. It's up to you to decide.
wp_redirect( $url, 301 );
exit;
}
}
}