What you’re trying to do, can be achived by simply using the parse_request
hook; no need for the custom rewrite rule and tag.
-
So remove this (and you should flush the rewrite rules — just visit the permalink settings page):
add_action( 'init', 'vacature_rewrite_rule' ); function vacature_rewrite_rule() { ... }
-
Then use this modified function which performs the redirection:
add_action( 'parse_request', 'wpd_catch_vacature_requests' ); function wpd_catch_vacature_requests( $query ) { if( ! is_admin() && preg_match( '#^redirect/([\w\-]+)$#', $query->request, $matches ) ){ $posts = get_posts( array( 'post_type' => 'vacatures', 'meta_key' => 'vacature_id', 'meta_value' => $matches[1], 'fields' => 'ids' ) ); // Redirect to the post. if( ! empty( $posts ) ){ // a valid post found wp_redirect( get_permalink( $posts[0] ) ); // Or otherwise, the homepage. Or you can remove this and a 404 page would be shown. } else { wp_redirect( home_url() ); } exit; } }