Woocommerce-在多供应商设置中按作者/用户对购物车中的产品进行排序

时间:2020-05-24 22:00:03

标签: php wordpress sorting woocommerce dokan

我有一家使用Dokan plugin的多供应商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>

(这是实际的产品循环,此处不重要,因为它们的排序顺序在上面的代码中发生)

关于如何获取购物车商品的作者信息的任何想法,都与获取类别有关?我很沮丧...

在此先感谢您的协助!

1 个答案:

答案 0 :(得分:1)

以下是有关如何按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>

相关:Display dokan vendor name on Woocommerce single product pages

相关问题