I have two custom post types that deal with people’s names. Right now, in browsing views, it just lists them all alphabetically and the pagination breaks them down by numbers, which isn’t terribly helpful when you’re trying to find a specific person.
Specifically, I’ve been asked to create pagination links for people that look like this:
- A-G
- H-M
- N-Q
- R-Q
My problem – I can’t figure out how I can query the custom post types by the first letter of one field. Then, I’m not sure how I can go about creating the pagination in this way. Does anybody have any suggestions? Thank you!
Interesting question! I solved it by expanding the
WHERE
query with a bunch ofpost_title LIKE 'A%' OR post_title LIKE 'B%' ...
clauses. You can also use a regular expression to do a range search, but I believe the database won’t be able to use an index then.This is the core of the solution: a filter on the
WHERE
clause:Of course you don’t want to allow random external input in your query. That is why I have an input sanitization step on
pre_get_posts
, which converts two query variables into a valid range. (If you find a way to break this please leave a comment so I can correct it)The final step is to create a pretty rewrite rule so you can go to
example.com/posts/a-g/
orexample.com/posts/a
to see all posts beginning with this (range of) letter(s).You can change the rewrite rule pattern to start with something else. If this is for a custom post type, be sure to add
&post_type=your_custom_post_type
to the substitution (the second string, which starts withindex.php
).Adding pagination links is left as an exercise for the reader 🙂
This will help you getting started. I don’t know how you would break the query at specific letter and then tell WP that there’s another page with more letters, but the following takes 99% of the rest.
Don’t forget to post your solution!
An answer using @kaiser’s example, with a custom post type as a function accepting alpha start and end params. This example is obviously for a short list of items, as it does not include secondary paging. I’m posting it so you can incorporate the concept into your
functions.php
if you like.Here is a way to do this by using the
query_vars
andposts_where
filters:Souce: https://gist.github.com/3904986
This is not so much an answer, but more a pointer to a direction to take. This will probably have to be 100% custom – and will be very involved. You’ll need to create a custom sql query (using the wpdb classs) and then for pagination you’ll pass these parameters to your custom query. You’ll probably need to also create new rewrite rules for this as well. Some functions to look into: