Support

Account

Home Forums General Issues how to sort a custom post type posts by count of using in another custom post ty

Helping

how to sort a custom post type posts by count of using in another custom post ty

  • I have a custom post type with name of “Thesis” and another custom post type with name of “Professors”.

    Each “Thesis” post have a custom field (ACF) with type of “Relation” that can select one custom post type of “Professors”.

    I want to show four professors who have been most involved in the writing of the thesis.

  • 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.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.