Sin descripción

class-wc-tracks-footer-pixel.php 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. /**
  3. * Send Tracks events on behalf of a user using pixel images in page footer.
  4. *
  5. * @package WooCommerce\Tracks
  6. */
  7. defined( 'ABSPATH' ) || exit;
  8. /**
  9. * WC_Tracks_Footer_Pixel class.
  10. */
  11. class WC_Tracks_Footer_Pixel {
  12. /**
  13. * Singleton instance.
  14. *
  15. * @var WC_Tracks_Footer_Pixel
  16. */
  17. protected static $instance = null;
  18. /**
  19. * Events to send to Tracks.
  20. *
  21. * @var array
  22. */
  23. protected $events = array();
  24. /**
  25. * Instantiate the singleton.
  26. *
  27. * @return WC_Tracks_Footer_Pixel
  28. */
  29. public static function instance() {
  30. if ( is_null( self::$instance ) ) {
  31. self::$instance = new WC_Tracks_Footer_Pixel();
  32. }
  33. return self::$instance;
  34. }
  35. /**
  36. * Constructor - attach hooks to the singleton instance.
  37. */
  38. public function __construct() {
  39. add_action( 'admin_footer', array( $this, 'render_tracking_pixels' ) );
  40. add_action( 'shutdown', array( $this, 'send_tracks_requests' ) );
  41. }
  42. /**
  43. * Record a Tracks event
  44. *
  45. * @param array $event Array of event properties.
  46. * @return bool|WP_Error True on success, WP_Error on failure.
  47. */
  48. public static function record_event( $event ) {
  49. if ( ! $event instanceof WC_Tracks_Event ) {
  50. $event = new WC_Tracks_Event( $event );
  51. }
  52. if ( is_wp_error( $event ) ) {
  53. return $event;
  54. }
  55. self::instance()->add_event( $event );
  56. return true;
  57. }
  58. /**
  59. * Add a Tracks event to the queue.
  60. *
  61. * @param WC_Tracks_Event $event Event to track.
  62. */
  63. public function add_event( $event ) {
  64. $this->events[] = $event;
  65. }
  66. /**
  67. * Add events as tracking pixels to page footer.
  68. */
  69. public function render_tracking_pixels() {
  70. if ( empty( $this->events ) ) {
  71. return;
  72. }
  73. foreach ( $this->events as $event ) {
  74. $pixel = $event->build_pixel_url();
  75. if ( ! $pixel ) {
  76. continue;
  77. }
  78. echo '<img style="position: fixed;" src="', esc_url( $pixel ), '" />';
  79. }
  80. $this->events = array();
  81. }
  82. /**
  83. * Fire off API calls for events that weren't converted to pixels.
  84. *
  85. * This handles wp_redirect().
  86. */
  87. public function send_tracks_requests() {
  88. if ( empty( $this->events ) ) {
  89. return;
  90. }
  91. foreach ( $this->events as $event ) {
  92. WC_Tracks_Client::record_event( $event );
  93. }
  94. }
  95. }