我创建了一个函数来显示一些带有短代码的产品,但我遇到的问题是错误消息没有显示在该页面上。例如,如果需要某些字段,则它仅显示在购物车/结帐页面上。
这是我的一些代码:
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()
函数。
我已经在下面复制了类似的Shortcode(用于测试目的),其中打印了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+
笔记:
- 在您的代码中,您使用2次
global $product;
...- 请记住,在短代码中,您永远不会回显或打印任何内容,但您会返回一些输出...
- 不要忘记在最后重置循环和查询。