WooCommerce 类别小部件中的锚链接

问题描述 投票:0回答:1

我使用一个代码在存档页面/shop上显示每个类别下的产品:

类别1

产品1 产品2 产品3

类别 2

产品1 产品2 产品3

这是我的代码:

<?php
foreach( get_terms( array( 'taxonomy' => 'product_cat' ) ) as $category ) :
    $products_loop = new WP_Query( array(
        'post_type' => 'product',

        'showposts' => -1,

        'tax_query' => array_merge( array(
            'relation'  => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'terms'    => array( $category->term_id ),
                'field'   => 'term_id'
            )
        ), WC()->query->get_tax_query() ),

        'meta_query' => array_merge( array(

            // You can optionally add extra meta queries here

        ), WC()->query->get_meta_query() )
    ) );

?>
    <h2 class="category-title"><?php echo $category->name; ?></h2>

    <?php
    while ( $products_loop->have_posts() ) {
        $products_loop->the_post();
        /**
         * woocommerce_shop_loop hook.
         *
         * @hooked WC_Structured_Data::generate_product_data() - 10
         */
        do_action( 'woocommerce_shop_loop' );
        wc_get_template_part( 'content', 'product' );
    }
    wp_reset_postdata(); ?>
<?php endforeach; ?>

我还使用标准小部件来显示 WooCommerce 类别。据我了解,该文件负责它 - woocommerce /includes/widget/class-wc-widget-product-categories.php。

如何修改此文件(functions.php 的代码)以添加锚链接?例如,在类别菜单中,我选择类别 2,页面向下移动到类别 2 及其产品。

我只是找不到现成的解决方案,所以我向你寻求帮助。我希望这段代码对其他用户有用。

php wordpress woocommerce
1个回答
1
投票

您需要添加一些 JavaScript 并添加“数据链接”属性以及类别术语的 href 在您的代码中

<h2 class="category-title" data-link="<?php echo get_term_link( (int) $category->term_id, 'product_cat' ); ?>"><?php echo $category->name; ?></h2>

我创建了一个片段来演示:

$('.product-categories .cat-item > a').on('click', function(e) {
  e.preventDefault();
  var href = $(this).attr('href');
  $('html, body').animate({
    scrollTop: $("[data-link='" + href + "']").offset().top
  }, 1000);
});
.left {
  float: left;
  width: 50%;
}
.right {
  float: right;
  width: 50%;
}

.category-wrapper {
  height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="left">
  <ul class="product-categories">
    <li class="cat-item">
      <a href="http://category1">Category 1</a>
    </li>
    <li class="cat-item">
      <a href="http://category2">Category 2</a>
    </li>
  </ul>
</div>
<div class="right">
  <div class="category-wrapper">
    <h2 class="category-title" data-link="http://category1">Category 1</h2>
  </div>

  <div class="category-wrapper">
    <h2 class="category-title" data-link="http://category2">Category 2</h2>
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.