Home › Forums › General Issues › how to sort a custom post type posts by count of using in another custom post ty › Reply To: how to sort a custom post type posts by count of using in another custom post ty
If this data already exists in a large quantity, doing what you want is not impossible, but in practice may not be possible.
Here’s what would be needed. 1) Do a WP_Query() to get every thesis post and loop through these posts. 2) Get the relationship from each thesis post. 3) Loop though the values of the relationship field and keep track of the count of all relationships to each professor. 4) Sort the professors in order of the count of thesis posts 5) Query the professor posts and order by this order that you’ve created.
With a limited amount of data the above is something that can be done. With a large amount of data the above is something that will likely cause performance issues on the page where it is done and could even potentially cause the page to time out.
If the project is still at a point where you can make a significant change, this is what I would do.
I would create an acf/save_post filter https://www.advancedcustomfields.com/resources/acf-save_post/ with priority set to 1 so that it runs before ACF saves the new value to the database. This filter would be for the thesis post where the relationship exists. I would create another post meta value attached to the professor post type that contains a count of all the thesis posts related to each professor. In the save_post filter I would look to see if any professors have been removed from the relationship, if they have I would get the count value from the professor, decrease the value and save it. I would then look to see if any professors have been added to the relationship field. If they have I would get the value from that professor, increase the count and save it. This would give you a field with a value that you can easily short the professors by. The only flaw I can see in this approach is the case where a thesis post is deleted, but you might be able to use a standard WP hook fired when a post is deleted to deal with this.
There might be other solutions.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Accordions are a great way to group related information while allowing users to interactively show and hide content. In this video, Damon Cook goes in-depth on how to create an accessible accordion block using ACF PRO’s Repeater field.https://t.co/RXT0g25akN— Advanced Custom Fields (@wp_acf) March 2, 2023
© 2023 Advanced Custom Fields.