1

I have a wordpress site using a custom post type "gallery" to show some photos. I can't find the right regex to match my url variables (i'm a novice with regex)

What i want to achieve is to get this form of url :

/custom_post_type_slug/custom_post_type_name/page_num/photo_id/

in my case it should give :

/gallery/name-of-gallery/1/15/

I've tried this regex :

add_rewrite_rule( 'gallery/(.+?)(?:/([0-9]+))?/([0-9]{1,2})/([0-9]{1,2})/?$', 'index.php?gallery=$matches[1]&page=$matches[2]&photo=$matches[3]','top' );

with no success.

When I test this rewrite rule with Query Monitor it tells that photo=$matches[3] and page is null.

If someone could give me an advise it will be very nice.

1 Answer 1

1

add_rewrite_rule() cannot automatically create that permalink structure for you. You should use wp_link_pages_link filter. E.g:

add_filter('wp_link_pages_link', function($link, $i)
{
  global $post, $photo_id;

  if ($photo_id && 'gallery' === $post->post_type)
    $link = $link . '/' . intval($photo_id) . '/';

  return $link;
}, PHP_INT_MAX, 2);

Then, you must use add_rewrite_tag() to make WordPress aware of photo query string:

add_action('init', function()
{
  add_rewrite_tag('%photo%', '([0-9]+)');
  add_rewrite_rule('^gallery/([^/]+)/([0-9]+)/([0-9]+)/?$', 'index.php?post_type=gallery&name=$matches[1]&page=$matches[2]&photo=$matches[3]', 'top');
}, 0, 0);
1
  • Thank you Dan9! The permalink structure is created in javascript with hmtl 5 history api so I think I don't need the wp_link_pages_link filter (the link with photo variable redirect to a gallery post type page which zoomed the desired photo with javascript). Thank's for the advice with add_rewrite_tag()
    – bvsmith
    Jul 23, 2016 at 10:17

Your Answer

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

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