Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
15.9k views
in Technique[技术] by (71.8m points)

php - How to get the product Id from a meta key and a meta value in WooCommerce

I am new to coding. But I did this and got an array of values as expected. Fantastic!

$thearray= get_post_meta( $product, $metakey, true );  

What if i had the meta_value (and of course the key) and wanted the post_ids as an array?

Thank you

question from:https://stackoverflow.com/questions/66067286/how-to-get-the-product-id-from-a-meta-key-and-a-meta-value-in-woocommerce

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't get a post Id from a defined meta key and meta value, as many post ids can have the same meta key and meta value.

You could use a custom SQL query only if the meta value for the meta key is unique, like:

function get_post_id_from_meta( $meta_key, $meta_value ) {
    return $wpdb->get_var( $wpdb->prepare("
        SELECT post_id 
        FROM {$wpdb->prefix}postmeta
        WHERE meta_key = '%s' 
        AND meta_value = '%s'", 
    $meta_key, $meta_value ) );
}

It should work (only if the meta value for the meta key is unique).

EXAMPLE USAGE:

$post_id = get_post_id_from_meta( '_color', 'Red' );

Get meta data from the WC_product Object

With the WC_product Object use the WC_Data method get_meta() from a defined meta key:

 $value = $product->get_meta('some_meta_key');

Get meta data from the Post Id (or product Id)

With WordPress get_post_meta() function from the product id from a defined meta key:

$value = get_post_meta( $product_id, 'some_meta_key', true );

where in both cases some_meta_key need to be replaced by the correct desired meta key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...