WooCommerce 添加数据属性以查看成功消息上的购物车按钮
WooCommerce add data- attribute to view cart button on success message
我已经设法更改成功消息上 查看购物车 按钮的 html 标记,以便我可以向其中添加 id="open_cart"
,但是我还想将 data-cart="open"
等数据属性添加到 html 输出,但是只返回 id
。
关于如何向其添加 data-
属性有什么想法吗?
function my_add_to_cart_message() {
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) :
$message = sprintf( '%s<a id="open_cart" data-target="open-cart" href="%s" class="button">%s</a>', __( 'Successfully added to cart.' , 'woocommerce' ), esc_url( get_permalink( woocommerce_get_page_id( 'cart' ) ) ), __( 'View Cart', 'woocommerce' ) );
return $message;
}
add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_message' );
这就是上面的函数returns:
<a id="open_cart" href="http://example.com/cart/" class="button wc-forward">Ver carrinho</a>
data-cart="open"
被忽略。简直烦人。
这里有一个关于为什么会发生这种情况的快速解释。
查看负责显示成功消息的 Woocommerce success.php 模板。
<?php foreach ( $messages as $message ) : ?>
<div class="woocommerce-message"><?php echo wp_kses_post( $message ); ?></div>
<?php endforeach; ?>
wp_kses_post() 函数通过检查允许的标签和属性来清理 $message 变量的输出。
这是您的解决方案:
将此代码段添加到您的 functions.php
function my_filter_allowed_html($allowed, $context){
if (is_array($context)) {
return $allowed;
}
if ($context === 'post') {
$allowed['a']['data-cart'] = true;
}
return $allowed;
}
add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2);
您需要连接到 wp_kses_allowed_html 过滤器并添加您的数据属性,以便 wp_kses_post() 函数不会将其过滤掉。
我已经设法更改成功消息上 查看购物车 按钮的 html 标记,以便我可以向其中添加 id="open_cart"
,但是我还想将 data-cart="open"
等数据属性添加到 html 输出,但是只返回 id
。
关于如何向其添加 data-
属性有什么想法吗?
function my_add_to_cart_message() {
if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) :
$message = sprintf( '%s<a id="open_cart" data-target="open-cart" href="%s" class="button">%s</a>', __( 'Successfully added to cart.' , 'woocommerce' ), esc_url( get_permalink( woocommerce_get_page_id( 'cart' ) ) ), __( 'View Cart', 'woocommerce' ) );
return $message;
}
add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_message' );
这就是上面的函数returns:
<a id="open_cart" href="http://example.com/cart/" class="button wc-forward">Ver carrinho</a>
data-cart="open"
被忽略。简直烦人。
这里有一个关于为什么会发生这种情况的快速解释。
查看负责显示成功消息的 Woocommerce success.php 模板。
<?php foreach ( $messages as $message ) : ?>
<div class="woocommerce-message"><?php echo wp_kses_post( $message ); ?></div>
<?php endforeach; ?>
wp_kses_post() 函数通过检查允许的标签和属性来清理 $message 变量的输出。
这是您的解决方案:
将此代码段添加到您的 functions.php
function my_filter_allowed_html($allowed, $context){
if (is_array($context)) {
return $allowed;
}
if ($context === 'post') {
$allowed['a']['data-cart'] = true;
}
return $allowed;
}
add_filter('wp_kses_allowed_html', 'my_filter_allowed_html', 10, 2);
您需要连接到 wp_kses_allowed_html 过滤器并添加您的数据属性,以便 wp_kses_post() 函数不会将其过滤掉。