I’m trying to create a WordPress plugin and I’m unable to display error messages using the admin_notices
feature.
function gbrew_notice_no_api_key() {
$url = admin_url('admin.php') . '?page=api-key';
?>
<div class="notice-info notice">
<p><?php _e("Please set up your client ID and client secret from the <a href='{$url}'>API Key</a> page first."); ?></p>
</div>
<?php
}
function gbrew_setup_menu() {
# Add the main menu option
add_menu_page('Spruce Beer Dashboard', 'Spruce Beer', 'manage_options', 'spruce-beer', 'gbrew_dashboard');
# Add the sub menu item to manage API keys
add_submenu_page('spruce-beer', 'API Key', 'API Key', 'manage_options', 'api-key', 'gbrew_manage_api_key');
}
function gbrew_dashboard() {
$client_id = get_option('untappd_client_id');
$client_secret = get_option('untappd_client_secret');
echo "<h1>Spruce Beer</h1>";
if(!empty($client_id) && !empty($client_secret)) {
var_dump($client_id);
var_dump($client_secret);
} else {
add_action('admin_notices', 'gbrew_notice_no_api_key');
}
}
# Add the plugin to the sidebar menu
add_action('admin_menu', 'gbrew_setup_menu');
3
Answers
already I think in your first function you can do better to return the HTML and maybe that will fix your problem
Your calling notices too late, they fire before admin_menu; try this
If your also running multisite, might be worth adding:
add_action('network_admin_notices', 'gbrew_notice_no_api_key');
as wellIt seems to me that the problem is in the
gbrew_dashboard
function.In the
else
statement you addgbrew_notice_no_api_key
toadmin_notices
, but the action is never called. Read this answer about howdo_action
andadd_action
work in tandem. In summary,I think the simplest solution looks like this:
Add
gbrew_notice_no_api_key
to the action no matter what, then call it withdo_action
.You could use a custom action (optional)
However, keep in mind that if you call
do_action('admin_notices')
, your plugin will call every function hooked toadmin_notices
, even if they belong to other plugins.If you are not OK with that, then you could add a custom action instead. Taking
gbrew
as a prefix to uniquely identify your own hooks, you could add a custom action that will be called only by your plugin. In that case, your code would look like this: