class-yoast-dismissable-notice.php 1.8 KB

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