当 woocommerce

互联网 行业动态 更新时间:2024-06-13 00:19:32

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!')函数,无论你设置钩子的优先级有多高,它们都不会显示任何内容。echoprint_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钩子的组合 使用cookieor local storage+ admin_noticeshook的组合 使用database+admin_notices钩子的组合

我认为,如果我们使用$_SESSION+ admin_noticeshook 方法,它会既安全又快速,甚至无需查询数据库以获取简单的文本字符串。这是我此刻能想到的解决方案:

代码进入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了类。您可以将其替换为、 或或。divred colornotice-warningnotice-infonotice-suess

这个答案已经在 woomerce 上进行了全面测试5.7并且工作正常。

更多推荐

woocommerce

本文发布于:2023-04-21 10:06:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/hyzx/b3240fb3d949a1e23b0152f15fcff4da.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:woocommerce

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!