[英]Get the id from a product custom field with linked products in WooCommerce
[英]How to get the grouped product ID from a linked product in woocommerce
我有一個分組產品product-1 ,它有許多鏈接產品:
-product-1(分組產品)
我想使用 product-2 的 ID 獲取 product-1 的 ID
您無法通過其子產品 ID 之一獲取特定分組產品的產品 ID,因為每個子產品都可以位於許多不同的分組產品中。
定義分組產品的子產品 IDS 的唯一數據位於wp_postmeta
表中, meta_key
_children
作為子產品 ID 數組。
現在,如果要用於檢索父分組產品 ID 的子產品 ID 只是一個唯一分組產品的子產品,則可以使用以下嵌入在函數中的 SQL 查詢:
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;
}
代碼位於活動子主題(或活動主題)的 function.php 文件中。 測試和工作。
用法
這里738
以下是兒童產品 ID 之一。 它也可以是通過變量傳遞的動態值。
$parent_grouped_id = get_parent_grouped_id( 738 );
ADDITION - 使用WC_Product_Query
獲取所有分組產品:
分組產品數組對象:
$grouped_products = wc_get_products( array( 'limit' => -1, 'type' => 'grouped' ) );
僅限IDS的分組產品數組:
$ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' => 'ids' ) );
我已經詳細闡述了@LoicTheAztec之前的正確答案,並為其添加了一些緩存以避免多個數據庫請求。 為我的項目寫的,只是與你分享 - 不要對我苛刻,我是新來的。 感謝@LoicTheAztec 的初步回答。
if ( ! function_exists( 'wc_get_parent_grouped_id' ) ) {
function wc_get_parent_grouped_id( $id ){
global $wpdb;
$cdata = wp_cache_get( __FUNCTION__, 'woocommerce' );
if ( ! is_array($cdata) )
$cdata = array();
if ( ! isset($cdata[$id]) ) {
$cdata[$id] = $parent_id = $children = false;
$qdata = $wpdb->get_row("SELECT post_id, meta_value
FROM $wpdb->postmeta
WHERE meta_key = '_children'
AND meta_value LIKE '%$id%'");
if ( is_object($qdata) ) {
$parent_id = $qdata->post_id;
$children = $qdata->meta_value;
if ( is_string($children) )
$children = unserialize($children);
if ( is_array($children) && count($children) > 0 )
foreach ($children as $child_id)
$cdata[$child_id] = $parent_id;
}
wp_cache_set( __FUNCTION__, apply_filters( __FUNCTION__ . '_filter', $cdata, $id, $parent_id, $children, $qdata ), 'woocommerce' );
}
return $cdata[$id];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.