1

I have a wordpress page at http://www.mysiteurl.com/pagename/ and I want any URL of the form http://www.mysiteurl.com/pagename/{any string here} to redirect or display my original page. How do I go about doing this? Is there a wordpress plugin that will make this simple for me?

1 Answer 1

2

This is quite possible. First off, Making pagename/{customString} resolve as the page itself instead of 404, then, you're free to decide whether to keep the URI as is and serve the page content, or redirect back somewhere e.g page permalink ( get_the_permalink() ):

add_action( "init", function(){
    $pagename = "pagename"; // page slug
    add_rewrite_rule(
        sprintf('^%s/([^/]*)/?', $pagename),
        sprintf('index.php?pagename=%s&pageParam=$matches[1]', $pagename),
        'top'
    );
});

add_filter( "query_vars", function( $vars ){
    $vars[] = "pageParam";
    return $vars;
});

add_action( "template_redirect", function(){
    if ( $param = get_query_var( "pageParam" ) ) {
        /* make sure param is not for comments pagination or smth similar */ 
        wp_redirect( get_the_permalink(), 301 );
        exit;
    }
});

If you don't wish to have the redirect then remove the code hooked into template_redirect (as of line:15). To get that custom string ( {any string here} ), simply call get_query_var( "pageParam" ).

Hope that helps.

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.