Created
May 29, 2022 11:29
-
-
Save qant/cdb1dd80f3a9d5f02decf553affe4ece to your computer and use it in GitHub Desktop.
Wordpress dismissible admin notice example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!defined('ABSPATH')) { | |
die('-1'); | |
} | |
if (!class_exists('ANT_NOTICE')) { | |
class ANT_NOTICE | |
{ | |
protected static $instance; | |
function add_notices() | |
{ | |
if (!get_user_meta(get_current_user_id(), 'ant_ajax-update-notice', true)) { | |
?> | |
<div id="ant_ajax-admin-rating" class="ant_ajax-notice notice is-dismissible" data-notice_id="ant_ajax-update-notice"> | |
<div class="notice-container" style="padding-top: 10px; padding-bottom: 10px; display: flex; justify-content: left; align-items: center;"> | |
<!-- <div class="notice-image"> | |
<img style="border-radius:50%;max-width: 90px;" src="<?php echo plugins_url('/assets/blah.png', ANT_PLUGIN_FILE); ?>" alt=""> | |
</div> --> | |
<div class="notice-content" style="margin-left: 15px;"> | |
<h2>I AM NOTICE!</h2> | |
<?php if (current_user_can('activate_plugins')) : ?> | |
<p>Activate plugin todo or other stuff</p> | |
<?php endif; ?> | |
</div> | |
</div> | |
</div> | |
<script> | |
(function($) { | |
$('.ant_ajax-notice').on('click', '.notice-dismiss', function(e) { | |
e.preventDefault(); | |
var notice_id = $(e.delegateTarget).data('notice_id'); | |
$.ajax({ | |
type: 'POST', | |
url: ajaxurl, | |
data: { | |
notice_id: notice_id, | |
action: 'ant_ajax_dismiss_notice', | |
}, | |
success: function(response) { | |
console.log(response); | |
}, | |
}); | |
}); | |
})(jQuery); | |
</script> | |
<?php | |
} | |
} | |
function ajax_dismiss_notice() | |
{ | |
if ($notice_id = (isset($_POST['notice_id'])) ? sanitize_key($_POST['notice_id']) : '') { | |
update_user_meta(get_current_user_id(), $notice_id, true); | |
wp_send_json($notice_id); | |
} | |
wp_die(); | |
} | |
function init() | |
{ | |
add_action('wp_ajax_ant_ajax_dismiss_notice', array($this, 'ajax_dismiss_notice')); | |
add_action('admin_notices', array($this, 'add_notices')); | |
} | |
public static function instance() | |
{ | |
if (!isset(self::$instance)) { | |
self::$instance = new self(); | |
self::$instance->init(); | |
} | |
return self::$instance; | |
} | |
} | |
ANT_NOTICE::instance(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment