I found this post (Create additional short URL with custom field and 301 redirect) and tried to do this with a custom post type I created but it aint working and I dont know what I am doing wrong in this case. I got URL's like this:
example.com/vacatures/junior-adviseur-kabels-en-leidingen-p565148-6/
and I want to create a short URL like this:
example.com/redirect/p565148-6/
And make a 301 redirect to
example.com/vacatures/junior-adviseur-kabels-en-leidingen-p565148-6/
I got a custom post type called "Vacatures" and a custom field "vacature_id".
I allready got this but that doesn't do anything.
add_action( 'init', 'vacature_rewrite_rule' );
function vacature_rewrite_rule() {
add_rewrite_tag( '%vacature_id%', '([a-zA-Z0-9]+)' );
add_rewrite_rule(
'^redirect([a-zA-Z0-9]+)?',
'index.php?vacature_id=$matches[1]',
'top'
);
}
add_action( 'parse_request', 'wpd_catch_vacature_requests' );
function wpd_catch_vacature_requests( $query ) {
if( ! is_admin() && isset( $query->query_vars['vacature_id'] ) ){
$the_post = new WP_Query(
array(
'post_type' => 'vacatures',
'meta_key' => 'vacature_id',
'meta_value' => $query->query_vars['vacature_id']
)
);
if( $the_post->have_posts() ){
wp_redirect( get_permalink( $the_post->post->ID ) );
} else {
wp_redirect( home_url() );
}
}
}