Opened 5 years ago
Last modified 6 months ago
#51787 new enhancement
Introduce dedicated function that retrieves post object by metadata
| Reported by: |
|
Owned by: | |
|---|---|---|---|
| Milestone: | Awaiting Review | Priority: | normal |
| Severity: | normal | Version: | 5.5.3 |
| Component: | Posts, Post Types | Keywords: | dev-feedback |
| Focuses: | Cc: |
Description
Just wanted to suggest a function I routinely use when building custom themes that utilize metadata.
<?php /** * Get post object from metadata. * * @since 5.5.3 * * @see get_posts() * * @param string $meta_key Meta key. * @param mixed $meta_value Meta value. * @param string $post_type Post type slug. Default 'post'. * * @return WP_Post|bool Post object if successful. False if not. */ function get_post_by_meta( $meta_key = '', $meta_value = '', $post_type = 'post' ) { $args = array( 'post_type' => $post_type, 'meta_key' => $meta_key, 'meta_value' => $meta_value, 'meta_compare' => '=', ); $posts = get_posts( $args ); if ( ! empty( $posts[0] ) ) { return $posts[0]; } return false; }
Change History (2)
#2
@
6 months ago
A good idea, if this would be useful for core. If not, easy to implement in userland.
And if it was to be added, I would suggest adding $meta_compare = '=' to the signature.
And being a bit smart, like including those posts where the meta_key "NOT EXISTS" in case the meta_value is empty. At least that is something I have implemented myself, and saves me setting up a complex meta query with relation "OR".
Note: See
TracTickets for help on using
tickets.
Hi @DaveyJake,
I have just come across this ticket, and as there hasn't been any activity on this in 5 years, I think it is safe to mark this ticket with the
closetag. However if there is anything more to be added here please do. 😃