简体   繁体   中英

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

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.

Thank you. The key is unique, yes. But I am struggeling. I cannot se that I am getting any values here. One record has this as a meta_value: a:3:{i:0;s:9:"Sri Lanka";i:1;s:5:"Tonga";i:2;s:19:"Trinidad and Tobago";}

And notship as the key.

I used your code and added a funtion like this:

add_action( 'woocommerce_before_main_content', 'trying');
function trying(){

$post_id = get_post_id_from_meta( 'notship', 'Tonga' );
    ?><span class="notshipped"><?php echo "Testing ",$post_id?></span><?php
}

But getting nothing. I also added global $wpdb to avoid error massage when running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM