Ruv*_*vee 7
好问题。这让我很好奇,让我深入研究了这WC_Admin_Notices
门课。这就是我发现的!
好吧,在我说WC_Admin_Notices
课程之前,我们先来说说你的第一个问题!
“通知没有出现”
因为当woomerce_order_status_changed
钩子触发时,没有与之关联的屏幕,而且不仅仅是通知,例如,如果您尝试执行 aprint_r
和/或 an ,echo
它们也不会显示任何内容,因为没有与该钩子关联的屏幕。你可以发现你打钩的唯一方法是使用die
函数。为了测试这一点,你可以这样做:
add_action('woomerce_order_status_changed', 'test', 99, 4);
function test($order_id, $old_status, $new_status, $order_object)
{
die('You hit the right hook!');
}
但是如果你用or替换die('You hit the right hook!')
函数,无论你设置钩子的优先级有多高,它们都不会显示任何内容。echo
print_r
WC_Admin_Notices
当你使用类时它会变得有趣。如果没有与woomerce_order_status_changed
钩子关联的屏幕,那么这个类是如何工作的?好吧,方法如下:
它有一个名为的属性
class-wc-admin-notices.php
班级
$notices
,它是一个简单的空数组。
当您调用add_custom_notice
方法时,它会将您提供的值存储到数据库和“选项”表中。键是“woomerce_admin_notice_{the name you give for example test}”,值是您定义的消息/通知。这就是它的全部作用!它将您的消息/通知存储到数据库中。
当你调用output_custom_notices
方法时,它会检查$notices
数组,并检查数据库中存储在选项表中的任何键值对,这些键值对使用我刚刚在数字 2 中提到的格式!html-notice-custom.php
然后,它使用在以下路径中调用的模板:
yourwebsite. > wp-content > 插件 > woomerce > 包含 > 管理 > 视图 > html-notice-custom.php
html-notice-custom.php
模板
该html-notice-custom.php
文件负责输出自定义通知的 html 标记,它会为它们提供一个名为的类,该类updated
将触发具有浅紫色的 css 规则。
所以WC_Admin_Notices
类的整体工作流程是:
将您的自定义消息存储到数组或数据库中
在屏幕加载时检索存储的键值对!
从技术上讲,这就是它所做的一切,好吧,用最简单的术语来说!
由于我们不想要那个自定义的浅紫色模板,我们可以使用WC_Admin_Notices
使用和编写我们自己的解决方案的工作流而不使用WC_Admin_Notices
类。
我们可以使用以下方法之一:
使用$_SESSION
+admin_notices
钩子的组合
使用cookie
or local storage
+ admin_notices
hook的组合
使用database
+admin_notices
钩子的组合
我认为,如果我们使用$_SESSION
+ admin_notices
hook 方法,它会既安全又快速,甚至无需查询数据库以获取简单的文本字符串。这是我此刻能想到的解决方案:
代码进入functions.php
您的活动主题的文件。
add_action('woomerce_order_status_changed', 'test', 99, 4);
function test($order_id, $old_status, $new_status, $order_object)
{
if ( $order_object && ($old_status != $new_status) )
{
$notice = 'This notice appears on the order page.';
session_start();
$_SESSION['your_custom_message_name'] = $notice;
}
}
add_action('admin_notices', 'your_them_displaying_custom_admin_notice');
function your_them_displaying_custom_admin_notice()
{
session_start();
if (isset($_SESSION['your_custom_message_name'])) {
?>
<div class='notice notice-error is-dismissible'>
<p><?php echo $_SESSION['your_custom_message_name'] ?></p>
</div>
<?php
unset($_SESSION['your_custom_message_name']);
}
}
笔记:
这仅在有订单$old_status
且 不等于时才有效$new_status
。
在$notice
变量中,我放置了原始文本,而不是 html,因为我们在钩子p
的 html 部分/模板中放置了一个标签。admin_notices
我已经为显示通知的标签使用notice-error
了类。您可以将其替换为、 或或。div
red color
notice-warning
notice-info
notice-suess
这个答案已经在 woomerce 上进行了全面测试5.7
并且工作正常。
更多推荐
woocommerce
发布评论