Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. class VirtualPage {
  2. /**
  3. * @var int $page_id The ID of the page where you would want to inject your custom template.
  4. **/
  5. var $page_id = 0;
  6.  
  7. /**
  8. * @var (mixed) $callback The callback function/method that will be called to replace the current post.
  9. **/
  10. var $callback = false;
  11.  
  12. function __construct( $page_id, $callback = false ) {
  13. $this->page_id = $page_id;
  14. $this->callback = $callback;
  15.  
  16. /**
  17. * Set the injector when there are posts found.
  18. **/
  19. add_action( 'posts_results', array( $this, 'posts_results' ), 10, 2 );
  20. }
  21.  
  22. function posts_results( $posts, $wp ) {
  23.  
  24. if ( $wp->is_main_query()
  25. && $wp->is_singular
  26. && count( $posts ) > 0
  27. && $posts[0]->ID == $this->page_id ) {
  28.  
  29. $found_posts = count( $posts );
  30.  
  31. /**
  32. * $wp->post_count holds the number of iterated posts. We'll make WP believe that all
  33. * posts are iterated.
  34. **/
  35. $wp->post_count = $found_posts;
  36.  
  37. /**
  38. * $wp->current_post holds the current post index. Setting it to the last post index
  39. * will immediately trigger `loop_end` action hook.
  40. **/
  41. $wp->current_post = $found_posts - 1;
  42.  
  43. add_action( 'loop_end', array( $this, 'loop_end' ) );
  44.  
  45. /**
  46. * Immediately remove the hook!
  47. **/
  48. remove_action( 'posts_results', array( $this, 'posts_results' ), 10, 2 );
  49. }
  50.  
  51. return $posts;
  52. }
  53.  
  54. function loop_end() {
  55. if ( $this->callback ) {
  56. // Call your callback here or do your stuff here
  57. call_user_func( $this->callback );
  58. }
  59.  
  60. /**
  61. * Immediately remove the hook!
  62. **/
  63. remove_action( 'loop_end', array( $this, 'loop_end' ) );
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement