[WordPress] Get Posts By Term and Sort Them


/ Published in: PHP
Save to your folder(s)

1. Get Posts however you see fit
2. Loop through the posts getting the terms from taxonomies and add them to the Post object
3. Sort the Array of Post Objects by the property you want them sorted by using sort_on_field()


Copy this code and paste it in your HTML
  1. <?php
  2. $args = array(
  3. 'numberposts' => -1,
  4. 'orderby' => 'title',
  5. 'order' => 'ASC'
  6. );
  7.  
  8. $posts = array();
  9. foreach( get_posts($args) as $post ):
  10. $terms = array();
  11. foreach(wp_get_object_terms( $post->ID, array('taxonomy1', 'taxonomy2') ) as $term) {
  12. //Works if there is only one term tagged in the post for this taxonomy. You need to figure out how best to handle multiple terms. You might try imploding() them in a comma seperated list: "Term 1, Term 2"
  13. $post[$term->taxonomy] = $term->name;
  14. }
  15. $posts[] = (object) $post;
  16. endforeach;
  17.  
  18. /**
  19. * Sort array of objects by field.
  20. *
  21. * @param array $objects Array of objects to sort.
  22. * @param string $on Name of field.
  23. * @param string $order (ASC|DESC)
  24. **/
  25. function sort_on_field(&$objects, $on, $order = 'ASC') {
  26. $comparer = ($order === 'DESC')
  27. ? "return -strcasecmp(\$a->{$on},\$b->{$on});"
  28. : "return strcasecmp(\$a->{$on},\$b->{$on});";
  29. usort($objects, create_function('$a,$b', $comparer));
  30. }
  31. /*
  32. Use `strcmp` for case-sensitive string comparing.
  33. Use `strcasecmp` for case-insensitive string comparing.
  34.  
  35. Source: http://www.php.net/manual/de/function.usort.php#104873
  36. */
  37.  
  38. sort_on_field($posts, 'taxonomy1', 'DESC');
  39.  
  40. foreach( $posts as $post ) {
  41. echo $post->taxonomy1;
  42. }
  43. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.