doulanli6146 2018-09-09 22:48
浏览 106
已采纳

如何从woocommerce中的链接产品中获取分组的产品ID

I have a grouped product product-1 , which has many linked products:

-product-1 (grouped product)

  • |__ product-2 (simple or variable product)
  • |__ product-3 (simple or variable product)

I want to get the ID of product-1 using the ID of product-2

  • 写回答

1条回答 默认 最新

  • dongliugu8843 2018-09-09 23:17
    关注

    You can't get the product Id of a particular grouped product through one of its children product ID, as each children can be in many different grouped products.

    The only data that define the children products IDS for a grouped product is located in wp_postmeta table arround the meta_key _children as an array of children product IDs.

    Now if the children product ID which you want to use to retrieve the parent grouped product ID is only the children of one unique grouped product, you can use the following SQL query embedded in a function:

    function get_parent_grouped_id( $children_id ){
        global $wpdb;
        $results = $wpdb->get_col("SELECT post_id FROM {$wpdb->prefix}postmeta
            WHERE meta_key = '_children' AND meta_value LIKE '%$children_id%'");
        // Will only return one product Id or false if there is zero or many
        return sizeof($results) == 1 ? reset($results) : false;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    USAGE

    Here below 738 is one the children Ids from a grouped product. It can also be a dynamic value through a variable…

    $parent_grouped_id = get_parent_grouped_id( 738 );
    

    ADDITION - Get all grouped products using a WC_Product_Query:

    1) Array of grouped products Objects:

    $grouped_products = wc_get_products( array( 'limit' => -1, 'type' => 'grouped' ) );
    

    1) Array of grouped products IDS only:

    $ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' => 'ids' ) );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?