Guest User

Untitled

a guest
Mar 20th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. add_action('init', function () {
  2. $q = new WP_Query([
  3. 'post_type' => 'shop_post',
  4. 'post_status' => 'publish'
  5. ]);
  6.  
  7. function toTimestamp($post) {
  8. return date_create_from_format('Y-m-d H:i:s', $post->post_date)->getTimestamp();
  9. }
  10.  
  11. remove_action('transition_post_status', 'switch_published_post', 10);
  12. {
  13. Ginq::from($q->get_posts())
  14. ->groupBy(function ($p) { return $p->post_author; }) // grouping posts by author
  15. ->where(function ($g) { return $g->count() > 1; }) // pick groups whose author wrote more than 1 post
  16. ->select(function ($g) { return $g->orderByDesc(function ($p) { return toTimestamp($p); }); }) // sort by timestamp
  17. ->select(function ($g) { return $g->drop(1)->toList(); }) // other than latest
  18. ->selectMany(function ($p) { return $p; }) // flatten
  19. ->select(function ($p) { return ['ID' => $p->ID, 'post_status' => 'draft']; }) // to draft
  20. ->all(function ($a) { return wp_update_post($a); }); // update them
  21. }
  22. add_action('transition_post_status', 'switch_published_post', 10, 3);
  23. });
  24.  
  25. function switch_published_post($new_status, $old_status, $post) {
  26.  
  27. if ($old_status == 'publish' || $new_status != 'publish') return;
  28.  
  29. $q = new WP_Query([
  30. 'post_type' => 'shop_post',
  31. 'post_status' => 'publish',
  32. 'author' => $post->post_author,
  33. ]);
  34.  
  35. remove_action('transition_post_status', 'switch_published_post', 10);
  36. {
  37. Ginq::from($q->get_posts())
  38. ->where(function ($p) use ($post) { return $p->ID != $post->ID; })
  39. ->select(function ($p) { return ['ID' => $p->ID, 'post_status' => 'draft']; })
  40. ->all(function ($a) { return wp_update_post($a); });
  41. }
  42. add_action('transition_post_status', 'switch_published_post', 10, 3);
  43. }
  44.  
  45. add_action('transition_post_status', 'switch_published_post', 10, 3);
Add Comment
Please, Sign In to add comment