在Woocommerce结账页面上,显示默认通知之前的自定义通知

4
我使用以下代码在结账页面上向未登录的 WooCommerce 用户(访客)显示自定义消息。
add_action('woocommerce_before_checkout_form', 'my_custom_message');
function my_custom_message() {
if ( ! is_user_logged_in() ) {
       wc_print_notice( __('This is my custom message'), 'notice' );
    }
}

这个论坛上的问题由@loictheaztec先生提出,与IT技术有关。我的之前的问题链接如下:
在Woocommerce结账页面为访客用户显示自定义消息

我想在代码中更改 woocommerce_before_checkout_form ,将我的消息移动到结账页面的顶部(第一行)。但是我不知道该如何做。 我只知道以下两个挂钩(与结账页面相关)

  • woocommerce_before_checkout_form
  • woocommerce_after_checkout_form

我添加了我的问题图片


我认为你需要做的是模板覆盖。覆盖woocommerce的默认设置并创建自己的模板,以提供更多功能。 - rai nalasa
1个回答

9
要在Woocommerce登录消息和添加优惠券消息之前在结账页面显示您的自定义消息,您需要使用以下代码:
add_action('template_redirect', 'my_custom_message');
function my_custom_message() {
    if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) {
        wc_add_notice( sprintf( __('This is my <strong>"custom message"</strong> and I can even add a button to the right… <a href="%s" class="button alt">My account</a>'), get_permalink( get_option('woocommerce_myaccount_page_id') ) ), 'notice' );
    }
}

代码放在您的活动子主题(或活动主题)的function.php文件中。已经测试并且有效。

在此输入图片描述


更简单的版本,仅适用于结帐页面的所有用户

add_action('template_redirect', 'my_custom_message');
function my_custom_message() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) {
        wc_add_notice( __('This is my custom message'), 'notice' );
    }
}

将代码放在您的活动子主题(或活动主题)的function.php文件中。 已测试并且有效。

在此输入图像描述


谢谢。工作正常。如果我将此代码转换为向所有网站用户(已登录和未登录)显示我的自定义消息,我该怎么做? - ahmadwp
1
你应该从if语句中删除! is_user_logged_in() && ... - LoicTheAztec
1
+1 - 你真的在SO上表现出色!很好!顺便提一下 - 我已经停止推荐将这样的函数放在主题的“functions.php”文件中,而是开始建议创建一个包含给定网站的“特殊需求”的小插件,以确保网站能够在主题更新或更改的情况下保持正常。 - random_user_name
2
@cale_b … 谢谢。注意:在自定义Woocommerce时有多种方法。但是始终使用子主题(用于覆盖Woocommerce模板和其他一些主题文件),并且它可以在更新后保留。现在插件更难处理,因此对于大多数用户来说,在子主题中使用function.php文件就足够了。 - LoicTheAztec
@ahmadsh 我在我的回答末尾为所有用户添加了一个更简单的代码提示,它会起作用。 - LoicTheAztec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接