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 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿