File: /var/www/dk/wp-content/themes/food/api/product/get_product_by_cate.php
<?php
/**
* 通过cate获取指定数量产品
*/
$tabs = new stdClass();
$args = array(
'taxonomy' => 'product_cat',
'hide_empty' => 0
);
$tabs->productCat = array();
$productTabs = get_terms('product_cat', $args);
foreach ($productTabs as $key => $value) {
if ($value->name != 'Uncategorized') {
array_push($tabs->productCat, $value->name);
}
}
//print_r($tabs->productCat);
$limit = empty($_POST['limit']) ? 6 : intval($_POST['limit']);
$page_num = empty($_POST['page_num']) ? 1 : intval($_POST['page_num']);
$result = [];
$args = array('category' => $_POST['cate'], 'orderby' => 'name', 'limit' => $limit, 'page' => $page_num);
$products = wc_get_products($args);
//$products = WC_Product_Query($args);
//$products = wc_get_products(array(
//// 'include' => array( 77, 78, 79 ),
// 'category' => array( '首頁專區' ),
// 'limit' => -1,
// 'status' => 'publish',
//));
//print_r($products);
foreach ($products as $product) {
$data = new stdClass();
$imageId = $product->get_image_id();
// var_dump($imageId);
$image_arr = wp_get_attachment_image_src($imageId, "full");
// var_dump($image_arr);
if (!empty($image_arr) && is_array($image_arr)) {
$image = $image_arr[0];
} else {
$image = "";
}
$data->id = $product->get_id();
$data->img_url = $image;
$data->product_name = $product->get_name();
$arr = $product->get_category_ids();
if (count($arr) >= 2) {
$catelist = [];
foreach ($arr as $a) {
$std = new stdClass();
$std = $wpdb->get_var($wpdb->prepare("select name from `wp_terms` where term_id=%d", $a));
array_push($catelist, $std);
}
$data->cate = $catelist;
$data->cate_single = $catelist[0];
} else {
$data->cate_single = $wpdb->get_var($wpdb->prepare("select name from `wp_terms` where term_id=%d", $product->get_category_ids()));
$data->cate = [$data->cate_single];
}
$data->product_price = $product->get_price();
$data->sale_price = $product->get_sale_price();
$data->regular_price = empty($product->get_regular_price()) ? '0' : $product->get_regular_price();
$data->description = $product->get_description();
array_push($result, $data);
}
$res = $result;