The first step is the rewrite rule. I’ve also added a rewrite tag so the custom query var will be parsed. You can also use the query_vars
filter for this instead.
add_action( 'init', 'tipp_rewrite_rule' );
function tipp_rewrite_rule() {
add_rewrite_tag( '%trick_nummer%', '([a-zA-Z0-9]+)' );
add_rewrite_rule(
'^tipp([a-zA-Z0-9]+)?',
'index.php?trick_nummer=$matches[1]',
'top'
);
}
The second step is to intercept these requests, load the post, and redirect. We use the parse_request
action for this, which passes a request object we can check for the presence of the trick_nummer
query var.
We then create a new WP_Query
to find the post with the matching value in the trick_nummer
meta key, and redirect there if one is found:
add_action( 'parse_request', 'wpd_catch_tipp_requests' );
function wpd_catch_tipp_requests( $query ) {
if( ! is_admin() && isset( $query->query_vars['trick_nummer'] ) ){
$the_post = new WP_Query(
array(
'meta_key' => 'trick_nummer',
'meta_value' => $query->query_vars['trick_nummer']
)
);
if( $the_post->have_posts() ){
wp_redirect( get_permalink( $the_post->post->ID ) );
} else {
wp_redirect( home_url() );
}
}
}