【问题标题】:Add content in between product rows in WooCommerce archives在 WooCommerce 档案中的产品行之间添加内容
【发布时间】:2020-06-19 12:05:43
【问题描述】:

我想在产品类别的第三个产品(可能是第六个、第九个...)之后显示一些内容。并非每个类别都有额外的内容或相同数量的内容。所以它应该是灵活的。

我发现an example 使用以下代码:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php get_template_part( 'template-parts/content' ); ?>    
        <?php if ( $wp_query->current_post == 1 ) { ?>
             <div>Put Ad Here</div>
        <?php } ?>    
<?php endwhile; endif; ?>

我将该代码添加到我的archive-product.php 中,如下所示:

if ( wc_get_loop_prop( 'total' ) ) {
    while ( have_posts() ) {
        the_post();

        /**
         * Hook: woocommerce_shop_loop.
         */
        do_action( 'woocommerce_shop_loop' );

        wc_get_template_part( 'content', 'product' );

        if ( $wp_query->current_post == 1 ) { 
            echo '<div>Put Ad Here</div>';
        }


    }
}

但它没有显示任何内容。 如果有一种方法可以在不接触模板文件的情况下添加这些内容,那就太好了。

有没有我可以使用的钩子?

【问题讨论】:

    标签: php wordpress woocommerce categories product


    【解决方案1】:

    更新 - 您可以使用以下挂钩函数代替覆盖模板文件,该函数将在每个产品行之间添加一个自定义内容完整行:

    add_action( 'woocommerce_shop_loop', 'action_woocommerce_shop_loop', 100 );
    function action_woocommerce_shop_loop() {
        // Only on producy cayegory archives
        if ( is_product_category() ) :
            
        global $wp_query;
        
        // Get the number of columns set for this query
        $columns = esc_attr( wc_get_loop_prop( 'columns' ) );
        
        // Get the current post count 
        $current_post = $wp_query->current_post;
        
        if ( ( $current_post % $columns ) == 0  && $current_post > 1 ) :
        
        ?>
        </ul>
        <ul class="columns-1" style="list-style:none; margin:0 0 3em;">
            <li style="text-align:center; padding:2em 1em; border: solid 1px #ccc;"><div class="banner"><?php _e("Custom content here"); ?></div></li>
        </ul>
        <ul class="products columns-<?php echo $columns; ?>">
        <?php
        endif; endif;
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

    • 一个问题:是否可以在列内添加自定义内容?否则我会在移动视图中遇到问题
    • 您在移动设备上应该不会有问题,因为列是动态的,例如在小型设备上您通常会有 1 个内容,每个 3 个产品。这只是一个示例,因此您可以轻松地操作 IF 语句以使其随心所欲。您还可以使用其他相关的 Wordpress 条件标签来检测您是否在设备上……
    • 我正在使用引导标记,将列类作为行。行内是 col 的所有产品。所以我只有一个&lt;ul&gt;,每个产品都在里面。有没有办法在&lt;ul&gt;里面添加内容?
    • 现在是的,您可以在一列中添加内容。但是你必须改变一下html结构,删除&lt;ul&gt;标签。
    • 是的,你可以做任何事情……想想看。只是结构和类选择器的问题
    【解决方案2】:

    由于我的菜鸟身份无法发表评论,但如果您更改了上面的代码,请稍作补充

    if ( ( $current_post % $columns ) == 0  && $current_post > 1 ) 
    

    if ( ( $current_post % $columns ) == 0  && $current_post%6==0 )
    

    内容将放置在每 6 个产品之后。显然,您可以使用任何数字。 认为这很有帮助,因为我找不到解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-05
      • 2019-06-22
      • 2017-06-25
      • 2019-10-21
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      相关资源
      最近更新 更多