php - 在页面上显示 Woocommerce 通知

标签 php wordpress woocommerce shortcode product

我创建了一个函数来显示一些带有短代码的产品,但我遇到的问题是错误消息未显示在该页面上。例如,如果某些字段是必需的,那么它只会显示在购物车/结帐页面上。

这是我的一些代码:

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();
}

我需要添加什么才能在使用短代码的页面上显示错误消息?

最佳答案

You need to use dedicated wc_print_notices() function, that displays Woocommerce notices. This function is hooked or used in woocommerce templates for that purpose.


要在您的短代码页面中激活 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:

  • In your code you are using 2 times global $product;
  • Remember that in a shortcode you never echo or print anything, but you return some output…
  • Don't forget to reset the loop and the query at the end.

关于php - 在页面上显示 Woocommerce 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631939/

相关文章:

java - 如何重复发布和接收数据但使应用程序仍然负责编辑

php - 当互联网消失时,如何将数据从mysql下载到android

Javascript 自动检查登录可用性

php - 在 wordpress 插件中使用 Composer 包

php - 从 Woocommerce 3 中的特定产品类别获取订单商品

css - Woocommerce - [product_categories] 简码 - 如何从列表中排除两个类别?

php - 具有复合主键的 Yii 模型

CSS异常使用:after

php - CSS 没有正确显示 .custom-logo,是 PHP 的问题吗?

php - 如何以编程方式获取 WooCommerce 中的所有产品?