How to create a php url redirection for nicer links

This solution works without creating new pages or changing anything.

We will:
1. Set up a new rewrite rule and add a new query variable
2. Catch that case in a ‘pre_get_posts’ hook, fetch the post we need and do the redirection

Note that if you have multiple posts with the same keyword_meta value, this might not work as planned. I have not implemented the checks for this, the first matching post will be selected.

Code should go into the functions.php or similar:

add_action( 'init',
    function () {
        add_rewrite_rule(
            '^(go)\/([^\/]+)$',
            'index.php?redirection=$matches[2]',
            'top'
        );

        add_filter( 'query_vars',
            function ( $vars ) {
                $vars[] = "redirection";

                return $vars;
            } 
        );
    }
);

add_action( 'pre_get_posts',
    function ( $query ) {
        if ( $redirection = get_query_var( 'redirection' ) ) {

            // Change this:
            $keyword_meta="keyword_meta_field_name";
            $redirection_url_meta="redirection_url_meta_field_name";
            $post_type="post";

            $args = [
                'meta_key'       => $keyword_meta,
                'meta_value'     => $redirection,
                'posts_per_page' => 1,
                'post_type'      => $post_type,
            ];

            $post_query = new WP_Query( $args );
            $posts      = $post_query->get_posts();

            // If no posts found, redirect back to referer
            if ( count( $posts ) < 1 ) {
                wp_safe_redirect( wp_get_referer() );
            }

            $redirection_url = get_post_meta( $posts[0]->ID, $redirection_url_meta, true );

            // If no redirection URL found, redirect back to referer
            if ( ! $redirection_url ) {
                wp_safe_redirect( wp_get_referer() );
            }

            // Finally, do the redirection
            if ( headers_sent() ) {
                echo( "<script>location.href="https://wordpress.stackexchange.com/questions/333996/$redirection_url"</script>" );
            } else {
                header( "Location: $redirection_url" );
            }
            exit;
        }

        return $query;
    }
);

Please do not forget to refresh your Permalinks in the dashboard (open Settings > Permalinks and click on Save Changes).

Leave a Comment