NEXT craftinamerica.org. Base setup for headless wordpress https://www.craftinamerica.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

related-items.php 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. function grab_ids_related_to_and_from($id_to_remove, $p2p_res) {
  3. $related_to_ids = array_map(function($post) {
  4. return (int)$post->p2p_to;
  5. }, $p2p_res);
  6. $related_from_ids = array_map(function($post) {
  7. return (int)$post->p2p_from;
  8. }, $p2p_res);
  9. $unfiltered = array_merge($related_to_ids, $related_from_ids);
  10. $deduped = array_unique($unfiltered);
  11. return array_diff( $deduped, array($id_to_remove) );
  12. }
  13. function prepare_related_items($args) {
  14. // Rearrange what fields get shown
  15. $collection = array();
  16. forEach( get_posts($args) as $item ) {
  17. $filtered = array();
  18. $filtered[id] = $item->ID;
  19. $filtered[slug] = $item->post_name;
  20. $filtered[type] = $item->post_type;
  21. $filtered[title] = $item->post_title;
  22. $filtered[excerpt] = $item->post_excerpt;
  23. $filtered[date] = $item->post_date;
  24. $filtered[content] = $item->post_content;
  25. $filtered[hero] = get_post_meta( $item->ID, 'hero_header', true );
  26. $collection[$item->ID] = $filtered;
  27. };
  28. wp_reset_postdata();
  29. return $collection;
  30. }
  31. function p2p_related_to($id, $type) {
  32. global $wpdb;
  33. $to_type = '%_to_' . $type;
  34. $from_type = $type . '_to_%';
  35. $res = $wpdb->get_results($wpdb->prepare(
  36. "SELECT * FROM wp_p2p
  37. WHERE p2p_from = %d
  38. OR p2p_to = %d",
  39. $id, $id
  40. ));
  41. $related_posts_ids = grab_ids_related_to_and_from($id, $res);
  42. // Use IDs to get posts from the wpdb
  43. $args = array(
  44. 'numberposts' => -1,
  45. 'post_type' => 'any',
  46. 'include' => $related_posts_ids
  47. );
  48. wp_reset_postdata();
  49. return prepare_related_items($args);
  50. }
  51. ?>