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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…