0

I've written a simple shortcode and using it on my gallery page. The URL for the page looks something like this:

http://mysite.dev/gallery/?view=category-name

but I want to be able to use

http://mysite.dev/gallery/category-name

When I use a URL like so, WP redirects to what seems the nearest match it can find. For example

http://mysite.dev/gallery/nature

redirects to

http://mysite/home/nature

I've tried implementing a rewrite rule:

function add_custom_rewrites()
{
    remove_filter('template_redirect', 'redirect_canonical');

    add_rewrite_rule('^gallery/([^/]*)/?$', 'index.php/gallery/?category=$matches[1]', 'top');
    add_rewrite_tag('%category%', '(.+)');

    flush_rewrite_rules();
}
add_action('init', 'add_custom_rewrites');

but the /gallery/category page always redirects to try and by some means find the nearest matching page.

Can anyone help, please?

1 Answer 1

1

To answer my own question, I didn't need to remove the 'redirect_canonical' filter, and I only needed to change the 2nd parameter for add_rewrite_rule. The resulting function looks as follows:

function add_custom_rewrites()
{
    add_rewrite_tag('%category%', '(.+)');
    add_rewrite_rule('^gallery/([^/]*)/?$', 'index.php?pagename=gallery&category=$matches[1]', 'top');

    flush_rewrite_rules();
}
add_action('init', 'add_custom_rewrites');
1
  • 2
    you don't want to flush rewrite rules on every request, only do it on plugin/theme activation, or manually by visiting the permalinks settings page. read flush_rewrite_rules for more info.
    – Milo
    Commented Nov 7, 2014 at 22:23

Your Answer

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

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