class-yoast-dismissable-notice.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin\Ajax
  6. */
  7. /**
  8. * This class will catch the request to dismiss the target notice (set by notice_name)
  9. * and will store the dismiss status as an user meta in the database.
  10. */
  11. class Yoast_Dismissable_Notice_Ajax {
  12. /**
  13. * Notice type toggle value for user notices.
  14. *
  15. * @var string
  16. */
  17. const FOR_USER = 'user_meta';
  18. /**
  19. * Notice type toggle value for network notices.
  20. *
  21. * @var string
  22. */
  23. const FOR_NETWORK = 'site_option';
  24. /**
  25. * Notice type toggle value for site notices.
  26. *
  27. * @var string
  28. */
  29. const FOR_SITE = 'option';
  30. /**
  31. * Name of the notice that will be dismissed.
  32. *
  33. * @var string
  34. */
  35. private $notice_name;
  36. /**
  37. * The type of the current notice.
  38. *
  39. * @var string
  40. */
  41. private $notice_type;
  42. /**
  43. * Initialize the hooks for the AJAX request.
  44. *
  45. * @param string $notice_name The name for the hook to catch the notice.
  46. * @param string $notice_type The notice type.
  47. */
  48. public function __construct( $notice_name, $notice_type = self::FOR_USER ) {
  49. $this->notice_name = $notice_name;
  50. $this->notice_type = $notice_type;
  51. add_action( 'wp_ajax_wpseo_dismiss_' . $notice_name, [ $this, 'dismiss_notice' ] );
  52. }
  53. /**
  54. * Handles the dismiss notice request.
  55. */
  56. public function dismiss_notice() {
  57. check_ajax_referer( 'wpseo-dismiss-' . $this->notice_name );
  58. $this->save_dismissed();
  59. wp_die( 'true' );
  60. }
  61. /**
  62. * Storing the dismissed value in the database. The target location is based on the set notification type.
  63. */
  64. private function save_dismissed() {
  65. if ( $this->notice_type === self::FOR_SITE ) {
  66. update_option( 'wpseo_dismiss_' . $this->notice_name, 1 );
  67. return;
  68. }
  69. if ( $this->notice_type === self::FOR_NETWORK ) {
  70. update_site_option( 'wpseo_dismiss_' . $this->notice_name, 1 );
  71. return;
  72. }
  73. update_user_meta( get_current_user_id(), 'wpseo_dismiss_' . $this->notice_name, 1 );
  74. }
  75. }