php - Woocommerce - 在多供应商设置中按作者/用户对购物车中的产品进行排序
问题描述
我有一个使用Dokan 插件的多供应商 Woocommerce 商店,我正在尝试根据供应商的身份将购物车分成几部分。例如:
- 供应商 1
- 产品C
- 产品B
- 供应商 2
- 产品A
Dokan 使用自定义角色“供应商”来扩展用户类,因此要获取供应商的 ID,我应该能够使用类似的东西:
$post_data = get_post( $cart_item['product_id'] );
$vendor_id = $post_data->post_author;
这确实有效,但它只会获得第一个供应商 ID,并且只会对购物车中的所有剩余产品重复该 ID。我知道这是因为我没有检索数组,但我在 WP 文档中找不到关于如何获取作者 ID 数组的任何内容(除了 wp_list_authors,但效果不佳)。
作为一个实验,只要我按类别排序,我就设法让拆分+排序工作,因为我可以使用 wp_get_post_terms()。我不能为作者数据复制这个,虽然......
当前(相关)代码如下:
<?php
$cat_sort = array();
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$cat_ids = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
foreach ( $cat_ids as $id ) {
$cat_sort[$id][$cart_item_key] = $cart_item;
}
}
ksort( $cat_sort );
$grouped_cart_items = array();
foreach ( $cat_sort as $cat_id => $cart_items ) {
$term = get_term( $cat_id, 'product_cat' );
?>
<tr>
<td colspan="6" class=""><strong><?php echo $term->name; ?></strong></td>
</tr>
(在这之后是实际的产品循环,在这里不应该很重要,因为它们的排序发生在上面的代码中)
关于如何以与获取类别相同的方式获取购物车产品的作者信息的任何想法?我好难过...
提前感谢您的任何帮助!
解决方案
以下是如何按 Dokan 供应商商店名称对购物车商品进行排序和显示的示例:
<table>
<?php
$car_items = WC()->cart->get_cart(); // Cart items
$items_sort = array(); // Initializing
// Loop through cart items
foreach ( $car_items as $cart_item_key => $cart_item ) {
// Get the vendor_id
$vendor_id = get_post_field( 'post_author', $cart_item['product_id'] );
$store_info = dokan_get_store_info( $vendor_id ); // Get the store data
$store_name = $store_info['store_name']; // Get the store name
// Set in multidimentional array the vendor and then the cart item key
$items_sort[$store_name][$cart_item_key] = $vendor_id;
}
if ( count($car_items) > 1 ) {
ksort( $items_sort ); // Sorting by vendor name
}
// 1st Loop by vendor name
foreach ( $items_sort as $store_name => $values ) {
$vendor_id = reset($values); // The vendor id
/$store_url = dokan_get_store_url( $vendor_id ); // Get the store URL (if needed)
?>
<tr>
<!-- Store name display -->
<td colspan="6" class="store-name"><strong><?php echo $store_name; ?></strong></td>
</tr>
<?php
// 2nd Loop the cart items for the vendor name
foreach( $values as $cart_item_key => $vendor_id) {
// Retreive the cart item from the cart item key
$cart_item = $car_items[$cart_item_key];
?>
<tr>
<!-- Product name display -->
<td colspan="6" class="product-name"><?php echo $cart_item['data']->get_name(); ?></td>
</tr>
<?php
} // End of 2nd Loop
} // End of 1st Loop
?>
</table>
推荐阅读
- sql - 需要oracle sql查询
- matplotlib - pycharm sciview 中的绘图与输出绘图不同
- javascript - 当我将 Div 作为 JavaScript 字符串时,输入按钮 ID 不起作用
- regex - 如何在 CSV 中转义双引号?
- scala - 不同表上的相同查询 - Scala Slick
- tcp - 客户端和服务器之间建立了TCP连接,但是还没有数据传输,然后客户端因为网络问题而宕机,服务器能知道吗?
- android - 媒体后台服务在 Android 9 (Api 28) 上被系统杀死
- c++ - 右值参数导致的多重实现
- reactjs - 如何水平对齐引导文本和按钮
- python - Beautifulsoup 和 Panda - 帮助修改多页代码