0

I want to create an additional shorter Version of my Post-Permalink with a 301 redirect to the real post URL.

The shorter Version of the URL should get its Custom Field I added as a post meta. It is called $trick_nummer

So I have:

mydomain.com/%postname%/

additionally I want:

mydomain.com/Tipp%trick_nummer%

I think it should be something like that:

    add_action("init", "tipp_rewrite_rule");

    function tipp_rewrite_rule() {

        add_rewrite_rule(

            '^tipp([a-zA-Z0-9]+?)',
            'index.php?$trick_nummer%',
            'top'
            );
    }

For example:

mydomain.com/i-am-the-post-name

And the shorter Link (trick_nummer would be '7')

mydomain.com/Tipp7

with a 301 redirect to

mydomain.com/i-am-the-post-name

I found this Question: Redirect short-form URL to long-form URL (post_id to post_id + post_name) But the difference I want is, that I need the number from my custom field.

And I would like to do this in the functions.php

  • the first step is to create an URL like index.php?trick_nummer=7 which redirect to the good post. this can be done in the action wp_loaded with testing $_GET["trick_nummer"]. – mmm Feb 24 '18 at 20:17
0

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() );
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.