修改Wooccommerce模板文件以按产品类别显示产品



我在这里拼命搜索并试图修改WooCommerce核心文件。

所以,我要做的是修改我的主题的woommerce.php文件,因为我想按类别在我的商店中显示产品。

到目前为止,我发现在主题根文件夹中的woommerce.php文件中有一行

<?php woocommerce_content(); ?>

其显示所有产品。然后,我发现mytheme/woocommerce/上的content-product.php文件正在为每个产品运行,简而言之,该文件包含每个产品的样式和类。换句话说,这个文件是在循环中运行的。

所以我现在知道我必须修改一些实际调用该文件的函数,我想把产品类别传递给该函数,这样我就可以显示我想要的产品。

通过挖掘,我发现在wp-content/plugins/woocommerce/included/wc-template-functions.php中有一个函数woococommerce_content((,代码如下

function woocommerce_content() {
if ( is_singular( 'product' ) ) {
while ( have_posts() ) :
the_post();
wc_get_template_part( 'content', 'single-product' );
endwhile;
} else {
?>
<?php if ( apply_filters( 'woocommerce_show_page_title', true ) ) : ?>
<h1 class="page-title"><?php woocommerce_page_title(); ?></h1>
<?php endif; ?>
<?php do_action( 'woocommerce_archive_description' ); ?>
<?php if ( woocommerce_product_loop() ) : ?>
<?php do_action( 'woocommerce_before_shop_loop' ); ?>
<?php woocommerce_product_loop_start(); ?>
<?php if ( wc_get_loop_prop( 'total' ) ) : ?>
<?php while ( have_posts() ) : ?>
<?php the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php woocommerce_product_loop_end(); ?>
<?php do_action( 'woocommerce_after_shop_loop' ); ?>
<?php else : ?>
<?php do_action( 'woocommerce_no_products_found' ); ?>
<?php
endif;
}
}

最后,我认为wc_get_loop_prop函数是初始化循环的函数,我正试图找到一种方法将参数传递给该函数(例如产品类别ID(,这样我就可以调用woommerce_content(118(,其中118是产品类别,并以我想要的方式显示我的产品。

有什么办法我能做到这一点吗?我在这一部分被困了很长时间,似乎找不到解决方案。

解决方案:

最后,我要做的就是简单地创建一个函数

function getProductsByCat($theCat) {
$args = array(
'post_type' => 'product',
'posts_per_page' => 50,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $theCat
)
)
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'product' );
endwhile;
} else {
return false;
}
return true;
}

在我的网站上的任何地方都可以通过等猫ID显示产品

<div class="col-md-12"><h4>Special Offers</h4></div>
<?php 
if(!getProductsByCat(191)){
//echo "<p>No products available.</p>";
}
?>

我希望这将对那些试图做同样事情的人有所帮助。

最新更新