I want to end up with url structure for galleries like the one below ;


as you see there will be two variables.

I separated templates like content-default and content-gallery.. So far it's OK. But what should i do to open a single gallery element page when user goes to this link?


You'll need to write a rewrite rule to parse the URL and pull out the value of gallery-name and gallery-item-name. This will be tricky as there is nothing to distinguish your proposed URL structure from a hierarchical page structure. If you can throw in something that is always the same for all gallery URLs like /gallery/<gallery-name>/<gallery-item-name>/.

Once you have a rewrite rule in place you can hook into the template_include filter, check if your two variables are set and then tell WordPress to include your gallery template.

Shiba Shake has a good tutorial on galleries with custom permalinks http://shibashake.com/wordpress-theme/wordpress-permalink-add

| improve this answer | |
  • Can't we write an if condition just like if(has_category('gallery')) {add this rule} ? '(has_category=='gallery')(.+?)/([^/]+)/?$' => 'index.php?name=$matches[1]&gallery_item=$matches[2] – Onur Çelik Aug 11 '16 at 10:10
  • It wouldn't work because has_category() checks against a $post and the rewrite rules are added way before we even know what $post the request is dealing with. The job of rewrite rules is to parse out variables from a URL that get sent to WP_Query which determines which posts should be displayed. – kingkool68 Aug 12 '16 at 15:10

OK. Here is my final solution.. Wordpress already has this opportunity for attached galleries.. Check if your theme already has a file called attachment.php otherwise create one and copy the content of single.php and modify.

This solution does the trick for me.

| improve this answer | |

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.