php - 使用 wp 查询获取所有 woocommerce 类别?
问题描述
我想获取所有带有标题和图像的 woocommerce 类别。之后,我想在首页上展示它们。避免 foreach 循环,因为我的首页设计类似于这样。[在此处输入图片描述][1]
<?php
$termSlug = array();
$tax_terms = get_terms('product_cat', array('hide_empty' => '0'));
foreach ( $tax_terms as $tax_term ):
$termSlug[] = $tax_term->slug;
endforeach;
$args = array(
'post_type' => 'product', //Post type event
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $termSlug
)
)
);
// The Query
$the_query = new WP_Query( $args );
//echo '<pre>';print_r($the_query);echo "</pre>";
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<?php
}
}else{
?>
<h2 style='font-weight:bold;color:#fff'>Nothing Found</h2>
</div>
<?php } echo '</div>';?>
[1]: https://i.stack.imgur.com/A98em.jpg
解决方案
以下代码段将在 WooCommerce 中获取产品类别。获取类别后,它将循环显示类别名称以及链接和类别图像。
$product_categories = get_terms( 'product_cat', 'hide_empty=0' );
if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
foreach ( $product_categories as $category ) {
?>
<div class="category-item">
<h4><a href="<?php echo esc_url( get_term_link( $category ) ); ?>"><?php echo esc_html( $category->name ); ?></a></h4>
<?php
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
?>
<?php if ( $image ) : ?>
<img src="<?php echo esc_url( $image ); ?>" alt="" />
<?php endif; ?>
</div>
<?php
}
}
推荐阅读
- reactjs - 从 localStorage 读取值后,如何以编程方式检查单选按钮
- html - 带有左右元素的电子邮件 HTML 导航,包括徽标、按钮和文本
- flutter - Content-Length 标头出现多次,最多允许出现一次
- javascript - 错误:对象作为 React 子对象无效(找到:带有键 {low, high} 的对象)
- python - re.search 模式和长/复杂字符串不匹配
- c# - 用作泛型参数时调用双“==”运算符
- c# - 如何从 FileSystemWatcher Onchanged 事件添加到队列并根据更改的文件触发不同的操作
- java - 自定义 Java 注释以忽略 CI 服务器上的集成测试
- sql - PL/SQL 瀑布桥图
- android - 从 FragmentContainerView 获取添加的子片段