[WordPress]按术语获取帖子并对其排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[WordPress]按术语获取帖子并对其排序相关的知识,希望对你有一定的参考价值。

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()
  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. ?>

以上是关于[WordPress]按术语获取帖子并对其排序的主要内容,如果未能解决你的问题,请参考以下文章

Wordpress 获取不在自定义分类术语中的帖子

在 Wordpress 后端保存 jQuery UI 可排序顺序

Wordpress 在自定义帖子类型存档页面上按日期排序

如何按列值的计数进行分组并对其进行排序?

将来自两个不同 wordpress 的帖子合并到一个按日期排序的帖子页面

SQL:Wordpress 用户按最新发布日期 (CPT) 排序