Is there a fast way to retrieve a specific post by a unique meta value? I could run a meta_query and then loop through the first value to get the post’s ID, but I am wondering if there is any other that I am overlooking.
Is it possible to add a column to the wp_posts table? Or is there some other way to add a second unique number to each post?
To explain I need to take a WooCommerce order (which is just a post type called ‘shop_order’) and send it to a 3rd party and they send back a unique reference from their system, which so far I have stored as meta. Normally I would send them the post ID as the order number, because when they send their info back with the post ID as order number it is easy to then set the post meta with the additional info they send.
However, there is another plugin ( called Sequential Order numbers ) which filters the post IDs to always show a sequential number. This makes great sense from a human-readable point of view. However, I can’t send this sequential order number because when it comes back to me I can’t use that value to update_post_meta
since it isn’t post ID in the database. If I send them the actual post ID and the two sides ever have to talk in person they won’t be referencing the same order ID number which would be confusing I think (much like this question).
So again to try to restate my question… is there a more efficient way to get a post by a second unique value that isn’t the post ID?
I am just incredible stupid here as this can be easily done by a simple WP_Query:
However, I decided to compare the actual generated SQL of the get_posts() with a ‘post_where’ filter solution which is:
with the actual generated SQL of the new WP_Query() solution which is:
So, both solutions are roughly equally efficient (the WP_Query() solution is probably slightly faster) but certainly not as efficient as human generated SQL.
get_post_by_meta_value()
returns an array of all posts of the specified post_type which have the specified meta_value for the specified meta_key which will be a 1 element array if the meta_value is unique.Yes.
$post->GUID
is a second identifier. It is actually WordPress’ designated Globally Unique IDentifier. Ref: Are all ID’s used unique?It can safely be referenced from your third-party service.
But you might want to keep
$post->ID
as a backup as well, in case someone inadvertedly tampers with the GUID (which might be more or less likely):https://wordpress.stackexchange.com/a/209833/71131