#community-help

Sorting WP Posts Alphabetically with Typesense

TLDR Adam wanted to sort WP posts alphabetically by last name. Jason suggested using sort_by parameter with Typesense, which worked successfully.

Powered by Struct AI

2

2

7
4mo
Solved
Join the chat
Jun 08, 2023 (4 months ago)
Adam
Photo of md5-d1ca9f479dc9860becc380edf02d7689
Adam
03:27 PM
so I have what may be a very higher-ed focused question - I want to use typesense to search WP posts with custom meta fields. each post represents a person (e.g. a faculty member). currently, when indexing the posts, they have a default_sorting_field of the post’s date converted to int32 by strtotime. however, I know the question will come up in a department meeting - is there any way to convert the “last name” field (which is obviously a string) into an integer which would allow me to list the results alphabetically when they’re initially fetched? so - does anyone know how to create an integer out of a string which would allow the documents to be ordered from the outset as if they were in alphabetical rather than date order? I fully admit that this is an odd question
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
04:47 PM
(This actually used to be a common question before we added the ability to sort by strings in Typesense natively!)

Instead of using the default_sorting_field you can set a default sort_by field as a search parameter to use the name field like this:

sort_by: text_match:desc,last_name:desc

1

Adam
Photo of md5-d1ca9f479dc9860becc380edf02d7689
Adam
05:24 PM
oooh ok I can try that. will that work on the initial load as well? my colleague and I were chatting and thinking about encoding each letter as a number 00 - 25. then those would represent the alphabetical order of the string
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
05:25 PM
I’m not sure how the wordpress plugin does it (if you’re using it), but from Typesense’s perspective, you can set a sort_by parameter on the very first request which populates records on page load
Adam
Photo of md5-d1ca9f479dc9860becc380edf02d7689
Adam
05:27 PM
perfect. I’m writing my own plugin for this project. to handle our particular context
05:38
Adam
05:38 PM
just checked it out with postman and that worked perfectly! even handled nested object syntax without a problem

1

06:10
Adam
06:10 PM
and confirmed it works in my plugin. got it working on the first try. really brilliant stuff here

1

1