【问题标题】:Get all products with specific meta_key whose meta_value is equal in WooCommerce获取具有特定元键的所有产品,其元值在 WooCommerce 中相等
【发布时间】:2021-04-14 13:44:56
【问题描述】:

在单个产品页面中,我想在自定义字段 (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;

任何帮助将不胜感激。

【问题讨论】:

    标签: php wordpress woocommerce metadata product


    【解决方案1】:

    使用它来获取 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>';
    }
    

    使用它来获取所有产品 ID,其中 meta_key = base_numbermeta_value = $some_variable

    // 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>';
        }
    }
    

    【讨论】:

    • 完美!完美无缝运行。
    猜你喜欢
    • 2021-01-24
    • 2021-11-24
    • 2018-10-11
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多