簡體   English   中英

獲取WooCommerce中meta_key相等的所有產品

[英]Get all products with specific meta_key whose meta_value is equal in WooCommerce

在單個產品頁面中,我想在自定義字段(base_number)中顯示具有相同值的所有產品的庫存數量,並且我認為這可以通過獲取這些產品的 id 來實現。

我嘗試過的沒有任何運氣

$product = wc_get_product( $product_id );

$same_base = get_posts( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'meta_key' => 'base_number',
    'meta_value' => get_post_meta(get_the_ID(), 'base_number', TRUE),
    'fields' => 'ids',
));

return $same_base;

任何幫助將非常感激。

使用它來獲取meta_key = base_number的所有產品

// Get WC_Product Objects
$products = wc_get_products( array(
    'limit'         => -1,
    'status'        => 'publish',
    'meta_key'      => 'base_number',
));

// Loop through
foreach( $products as $product ) {
    // Get product ID
    $product_id = $product->get_id();
    echo '<p>Product ID: ' . $product_id . '</p>';
    
    // Get stock quantity
    $stock_quantity = $product->get_stock_quantity();
    echo '<p>Stock quantity: ' . $stock_quantity . '</p>';
}

使用它來獲取meta_key = base_number的所有產品,假設meta_value = 30

// Get WC_Product Objects
$products = wc_get_products( array(
    'limit'         => -1,
    'status'        => 'publish',
    'meta_key'      => 'base_number',
    'meta_value'    => 30
));

// Loop through
foreach( $products as $product ) {
    // Get product ID
    $product_id = $product->get_id();
    echo '<p>Product ID: ' . $product_id . '</p>';
    
    // Get stock quantity
    $stock_quantity = $product->get_stock_quantity();
    echo '<p>Stock quantity: ' . $stock_quantity . '</p>';
}

使用它來獲取meta_key = base_numbermeta_value = $some_variable的所有產品 ID

// Some variable
$some_variable = 25;

// Get product ID's
$product_ids = wc_get_products( array(
    'limit'         => -1,
    'status'        => 'publish',
    'meta_key'      => 'base_number',
    'meta_value'    => $some_variable,
    'return'        => 'ids'
));

// Loop through
foreach( $product_ids as $product_id ) {
    echo '<p>Product ID: ' . $product_id . '</p>';
}

要獲取您當前正在查看的產品的base_number ,請使用

// Get the global product object
global $product;

// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
    // Get meta
    $base_number = $product->get_meta( 'base_number' );
    
    // NOT empty
    if ( ! empty ( $base_number ) ) {
        echo '<p>Base number: ' . $base_number . '</p>';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM