Woocommerce 从类别中获取产品 ID
Woocommerce get product ID's from Category
所以在我的分类模板上-product_tag.php,我想从类别中获取所有产品 ID。
这是我目前的做法
<?php
$post_ids = array();
$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'dog-collars', 'orderby' => 'rand' );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$post_ids[] = get_the_ID();
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_query();
print_r($post_ids);
?>
我可以遍历 product_cat,将 id 拉入一个数组,然后在页面的下方使用 foreach 和 WC 产品工厂来处理数据,以我希望的方式向用户显示数据。
我的问题是我需要循环基于类别是动态的,但我不明白该怎么做。
我确实认为我可以从 url
中获取类别名称
<?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
抓住它并解析以获取最后一个,即类别名称,然后打印到循环中
但这似乎是一种非常糟糕的做法。
我想要的在args里
$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'DYNAMICHERE', 'orderby' => 'rand' );
我希望能够根据我所在的类别动态填充product_cat
任何帮助或建议/指出我正确的方向将不胜感激
使用get_query_var( 'product_cat' )
.
所以在我的分类模板上-product_tag.php,我想从类别中获取所有产品 ID。
这是我目前的做法
<?php
$post_ids = array();
$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'dog-collars', 'orderby' => 'rand' );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$post_ids[] = get_the_ID();
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_query();
print_r($post_ids);
?>
我可以遍历 product_cat,将 id 拉入一个数组,然后在页面的下方使用 foreach 和 WC 产品工厂来处理数据,以我希望的方式向用户显示数据。
我的问题是我需要循环基于类别是动态的,但我不明白该怎么做。
我确实认为我可以从 url
中获取类别名称<?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>
抓住它并解析以获取最后一个,即类别名称,然后打印到循环中
但这似乎是一种非常糟糕的做法。
我想要的在args里
$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'DYNAMICHERE', 'orderby' => 'rand' );
我希望能够根据我所在的类别动态填充product_cat
任何帮助或建议/指出我正确的方向将不胜感激
使用get_query_var( 'product_cat' )
.