Emerson Maningo
Emerson Maningo

Reputation: 2279

How to check if custom field exist even if meta value is empty in WordPress

I have a pretty working condition to check if custom field exist, this is the line:

if (((get_post_meta($post->ID, $my_metakey, TRUE))=='')

However as you have noticed, it will only be effective to check for meta key if its value is set to empty.

I would like to know how to check if the custom field name/meta key already exist in the database even if I set the meta value to empty or blank at defaults.

Is there an efficient approach of doing this with WordPress? Thanks for any tip.

Update: Also this one won't work:

<?php if (strlen(get_post_meta($post->ID, $metakey, true)) > 0) : ?>

As it is similar to checking if the custom field is empty.

Upvotes: 4

Views: 6374

Answers (2)

Max
Max

Reputation: 176

With WP 3.3.0 there is a better way: use cache and apply filters

 metadata_exists( 'post', $post->ID, $my_metakey )

Upvotes: 15

barakadam
barakadam

Reputation: 2259

The custom fields values are stored in wp_postmeta WordPress database table. So just use this :

$test = $wpdb->get_results( "SELECT meta_key FROM wp_postmeta where meta_key='name_of_custom_field'" );
if (($wpdb->num_rows)>0) {
    // custom field exists
}
else {
    // field does not exist 
}

Upvotes: 4

Related Questions