我创建了一个功能来显示一些带有短代码的产品,但我遇到的问题是错误消息没有显示在该页面上。例如,如果某些字段是必需的,那么它仅显示在购物车/结账页面上。
这是我的一些代码:
while ( $query->have_posts() ) : $query->the_post();
global $product;
?>
<div style="border-bottom:thin dashed black;margin-bottom:15px;">
<h2><?php the_title(); ?> <span><?php echo $product->get_price_html();?></span></h2>
<p><?php the_excerpt();?></p>
<?php global $product;
if( $product->is_type( 'simple' ) ){
woocommerce_simple_add_to_cart();
}
我需要添加什么才能在使用短代码的页面上显示错误消息?
你需要使用专用的wc_print_notices()函数,显示 Woocommerce 通知。为此目的,此函数在 woocommerce 模板中被挂钩或使用。
要使 WooCommerce 通知在您的短代码页面中激活,您需要在您的短代码中添加以下内容wc_print_notices()功能。
我在下面复制了与您类似的简码(用于测试目的)woocommerce 通知的打印位置:
if( !function_exists('custom_my_products') ) {
function custom_my_products( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts( array( 'ppp' => '12', ), $atts, 'my_products' );
ob_start();
// HERE we print the notices
wc_print_notices();
$query = new WP_Query( array(
'post_type' => 'product',
'posts_per_page' => $atts['ppp'],
) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
global $product;
?>
<div style="border-bottom:thin dashed black;margin-bottom:15px;">
<h2><?php the_title(); ?> <span><?php echo $product->get_price_html();?></span></h2>
<p><?php the_excerpt();?></p>
<?php
if( $product->is_type( 'simple' ) )
woocommerce_simple_add_to_cart();
endwhile;
endif;
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="my-products">' . ob_get_clean() . '</div>';
}
add_shortcode( 'my_products', 'custom_my_products' );
}
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
这已经过测试并且适用于 WooCommerce 3+
Notes:
- 在您的代码中您使用了 2 次
global $product;
…
- 请记住,在短代码中,您永远不会回显或打印任何内容,但您return一些输出...
- 不要忘记在最后重置循环和查询。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)