WordPress.org

Make WordPress Core

Opened 8 months ago

#51787 new enhancement

Introduce dedicated function that retrieves post object by metadata

Reported by: DaveyJake 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 (0)

Note: See TracTickets for help on using tickets.