1

How do I check whether a post with a certain meta value exists?

For instance, check if a post exists with _sku = 1?

1 Answer 1

3

One way would be to use get_posts function:

$posts_with_meta = get_posts( array(
    'posts_per_page' => 1, // we only want to check if any exists, so don't need to get all of them
    'meta_key' => '_sku',
    'meta_value' => '1',
    'fields' => 'ids', // we don't need it's content, etc.
) );

if ( count( $posts_with_meta ) ) {
    // they exist
}

Currently it will search for published posts. You can customize it to your needs, so you can search for different types of posts or for posts with different statuses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.