我使用以下代码来获取我的WordPress网站中的WooCommerce表单的产品类别列表:
<?php
$taxonomy = 'product_cat';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 0; // 1 for yes, 0 for no
$title = '';
$empty = 0;
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
?>
<?php $all_categories = get_categories( $args );
//print_r($all_categories);
foreach ($all_categories as $cat) {
//print_r($cat);
if($cat->category_parent == 0) {
$category_id = $cat->term_id;
?>
<?php
echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?>
<?php
$args2 = array(
'taxonomy' => $taxonomy,
'child_of' => 0,
'parent' => $category_id,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title,
'hide_empty' => $empty
);
$sub_cats = get_categories( $args2 );
if($sub_cats) {
foreach($sub_cats as $sub_category) {
echo $sub_category->name ;
}
} ?>
<?php }
}
?>
这可以很好地工作,并返回产品类别的列表。我现在一直在尝试获取一个特定类别的产品列表。
示例:使用cat_id=34
获取的所有产品。
我知道产品是以帖子的形式存储的,并且一直试图做到这一点,但似乎做不到。
如何获取特定类别的产品列表?
发布于 2014-01-10 03:20:27
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10,
'product_cat' => 'hoodies'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
endwhile;
wp_reset_query();
?>
这将列出所有产品缩略图和名称及其到产品页面的链接。根据需要更改类别名称和posts_per_page。
发布于 2018-05-21 23:36:05
请勿使用WP_Query()
或get_posts()
。从WooCommerce文档中:
wc_get_products和WC_Product_Query提供了一种检索产品的标准方法,该方法可以安全地使用,并且不会因为未来WooCommerce版本中的数据库更改而中断。构建定制的WP_Queries或数据库查询可能会破坏WooCommerce未来版本中的代码,因为数据会向定制表移动,以获得更好的性能。
您可以像这样检索所需的产品:
$args = array(
'category' => array( 'hoodies' ),
'orderby' => 'name',
);
$products = wc_get_products( $args );
注意: category参数接受一个slugs数组,而不是ID。
发布于 2014-01-10 03:05:19
<?php
$args = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
$products = get_posts( $args );
?>
这应该会获取你想要的所有产品,我可能把post类型弄错了,虽然我不太记得post类型是用来做什么的。它将返回一个产品数组
https://stackoverflow.com/questions/21028830
复制相似问题