【问题标题】:Alter rendered html in WooCommerce success message在 WooCommerce 成功消息中更改呈现的 html
【发布时间】:2018-03-07 21:38:59
【问题描述】:

在 WooCommmerce 中将产品添加到购物车后,您会收到一条通知:

“产品”已添加到您的购物车。查看购物车

首先呈现链接元素(查看购物车),其次呈现字符串元素(“产品”已添加到您的购物车。)。我想切换这些元素,以便首先呈现字符串,然后呈现链接。

HTML:

<div class="woocommerce-message" role="alert">
<a href="http://example.com/cart/" class="button wc-forward">View cart</a> “Happy Ninja” has been added to your cart.</div>
</div>

尝试追踪代码但卡在: https://github.com/woocommerce/woocommerce/blob/master/templates/notices/success.php

寻找添加到functions.php的sn-p

【问题讨论】:

  • 你为什么要这样做?因为在视觉上(在 WooCommerce 版本 3.3.3 上),“查看购物车”链接显示在通知框的右侧,而“字符串元素”则显示在左侧。当然,除非默认外观/CSS 由主题、插件或您修改。
  • 我认为 ux 明智的是先有字符串然后再链接。在桌面上可以正常工作(是的,显示在右侧),但在移动设备上很难做到正确。之后所有设备都渲染链接不是更容易吗?
  • 好吧,我不是 UX 方面的专家,所以我将跳过回答这个问题。不过我有一个 PHP sn-p 你可以试试。
  • 是的,我们向wc_add_to_cart_message_html hook 添加了一个过滤器。 =)

标签: php wordpress woocommerce


【解决方案1】:

试试这个:

add_filter( 'wc_add_to_cart_message_html', function( $message ) {
    return preg_replace(
        // Or use ^(<a href=".+?" class="button wc-forward">.+?</a>) *(.+)
        '#^(<a href=".+?" class="button wc-forward">.+?</a>) +(.+)#',
        '$2 $1',
        trim( $message )
    );
} );

如果没有插件(或者如果主题没有)修改默认 HTML 标记(如您在 line #121line #123 上看到的那样),上面的代码应该可以正常工作。

[EDIT #3] 或者,您可以完全重新生成消息/HTML,如下例所示:

add_filter( 'wc_add_to_cart_message_html', 'my_wc_add_to_cart_message_html', 10, 2 );
function my_wc_add_to_cart_message_html( $message, $products ) {
    $titles = array();
    $count  = 0;

    foreach ( $products as $product_id => $qty ) {
        $titles[] = ( $qty > 1 ? absint( $qty ) . ' &times; ' : '' ) . sprintf( _x( '&ldquo;%s&rdquo;', 'Item name in quotes', 'woocommerce' ), strip_tags( get_the_title( $product_id ) ) );
        $count += $qty;
    }

    $titles     = array_filter( $titles );
    $added_text = sprintf( _n( '%s has been added to your cart.', '%s have been added to your cart.', $count, 'woocommerce' ), wc_format_list_of_items( $titles ) );

    // Output success messages - the "View cart" or "Continue shopping" link comes after the product link/info.
    if ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
        $return_to = apply_filters( 'woocommerce_continue_shopping_redirect', wc_get_raw_referer() ? wp_validate_redirect( wc_get_raw_referer(), false ) : wc_get_page_permalink( 'shop' ) );
        $message   = sprintf( '%s <a href="%s" class="button wc-forward">%s</a>', esc_html( $added_text ), esc_url( $return_to ), esc_html__( 'Continue shopping', 'woocommerce' ) );
    } else {
        $message   = sprintf( '%s <a href="%s" class="button wc-forward">%s</a>', esc_html( $added_text ), esc_url( wc_get_page_permalink( 'cart' ) ), esc_html__( 'View cart', 'woocommerce' ) );
    }

    return $message;
}

希望有帮助!

【讨论】:

  • 太棒了!编辑#3正是我正在寻找的。谢谢!
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 2021-08-28
  • 2019-09-25
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多