Reputation: 121
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
Upvotes: 2
Views: 4886
Reputation: 254378
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.
Upvotes: 2