0

I wish to add a userq parameter at the end of a URL with the username such as john. I wish to change,

example.com/user/john

to,

example.com/user/index.php?userq=john

I tried this and this and they don't work.

add_action('init', 'user_profile_rewrite');
function user_profile_rewrite() {
        global $wp, $wp_rewrite;
        $wp->add_query_var('userq');
        $rule = '^user/([^/]*)/?';
        $rewrite = 'user/index.php?userq=$matches[1]';
        add_rewrite_rule( $rule, $rewrite, 'top' );
        $wp_rewrite->flush_rules();
}

I think the error has something to do with user/index.php? so I tried removing the word user by changing to index.php?... but the URL remains like the original. How to solve this?

5
  • can you be more specific? You mentioned they didn't work but didn't go into detail. Also that's not how you add a new query variable to the list, there's a dedicated filter for it, and the add_query_var function. It's also very bad practice to flush rewrite rules on the init hook. Have you used one of the rewrite rule inspector plugins? The examples in the official documentation should work better than the answers you linked to
    – Tom J Nowell
    Commented Apr 6, 2023 at 15:15
  • @TomJNowell I mean when I go to 'example.com/user/john' I still get 'example.com/user/john' URL in return, not 'example.com/user/index.php?userq=john' and I also tried the 'add_query_var ' and I still don't get my URL to be rewritten.
    – ratib90486
    Commented Apr 6, 2023 at 21:12
  • @TomJNowell Thanks to you, I just installed the plugin and it says there's a rule 'user/([^/]+)/?$' and rewritten to be 'index.php?page_id=12140&um_user=$matches[1]' so I wonder if the reason I can't get it to work is that the URL has already been rewritten.
    – ratib90486
    Commented Apr 6, 2023 at 21:17
  • are you expecting the URL in the address bar to change? Rewrite rules are not redirects, they always map a pretty URL in to the form index.php?quervar=value&etc..., they can't map to arbitrary files, and they can't be used to create redirects to other URLs. Rewrite rules also have a priority/order, but I can guarantee the way that you did it in your questions code, and the way the question/answers you linked to do it, are incorrect. A briefest of looks at the official documentation for add_rewrite_rules shows a far superior example that is safer, more reliable, and honestly easier to write
    – Tom J Nowell
    Commented Apr 7, 2023 at 8:41
  • also note that rewrite rules won't change the permalinks of posts and terms, the system for figuring out the URL of a post, and the system for figuring out the post from a URL are independent of eachother. As is canonical redirects
    – Tom J Nowell
    Commented Apr 7, 2023 at 8:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.