I want to create custom post types with multiple views based on URL.
E.g., suppose I have a “Product” post type. I would like to have something like the following:
- http://example.com/products/product_name <– Regular view of the product/regular template
- http://example.com/products/product_name/detailed <– Expanded view, extra info, more theme elements, widgets, etc.
- http://example.com/products/product_name/summary <– Quick view, less info, minimal page elements
- http://example.com/products/product_name/xml <– Content wrapped in XML
I would be fine with this as well:
Is it possible to represent a page/post as different URLs, each with a different view of the same data? Would this require a lot of modification?
What you want is a rewrite endpoint.
You’re already familiar with these. WordPress’ urls that end with
feed
are simple a rewrite endpoint, and you can add your own!add_rewrite_endpoint
takes two arguments: the endpoint you want, and the “mask” of where you want it to go. “mask” is just a number that you can do some bitwise math with to specify where you want the endpoint to go. As of WP 3.4 you can specify a customep_mask
when registering a post type.The basic gist: hook into
init
, calladd_rewrite_endpoint
, specify the custom EP mask of your post type. Here’s a really quick example (as a plugin here):The only downside to this is that endpoints are meant to be used as
/<endpoint_name>/<some_value>
. So without<some_value>
present the endpoint technically wouldn’t work — hence the filter hooked intorequest
. Check if the endpoint is set, and set it to true if it is.That also means that
/detailed/asdf
would work just as well as/detailed/
. Not a huge issue to but something to be aware of.On the front end side of things, you can check to see if the endpoint exists by using
get_query_var
:add_rewrite_endpoint
adds query variables with the same name as you specified for the endpoint.detailed
in this case.Probably not the best way to do it, but one way to get there is: set your CPT to hierarchical, so it will allow parents, and allow it to have templates using either this, this or another approach.
Once you’ve set up things this way, organize your CPTs so that each one is parent to the “detailed”, “summary” and “xml” sub-pages (i’m almost certain you can do this automagically, hooking to the saving post hook which name i can’t rememember right now).
With that, you can just adjust templates for each “kind” of subpage (you may want to id them with custom values) so that they collect the info the way you want it.