2

Is it possible to check if a custom field exists for a given post within the loop? For example, I'm using functions like get_post_meta($post->ID, 'Company', true); preceded by a <h4> tag, but I'd like to check to make sure that there is a value for the custom field "Company" before writing the <h4>. Is this possible?

1
  • I love how things asked 11 years ago can still be so relevant.
    – Lisa
    Jul 13 at 23:03

1 Answer 1

8

The WP get_ methods are here to retrieve data, not to display them. You can easily check the var - containing the data - before adding your head tags:

$my_post_meta = get_post_meta($post->ID, 'Company', true);
if ( ! empty ( $my_post_meta ) )
    echo '<h4>'.$my_post_meta.'</h4>';
8
  • 2
    No, it just checks if value is empty.
    – T.Todua
    Feb 25, 2017 at 22:55
  • @T.Todua The OP asked (in the year 2011): "[…] I'd like to check to make sure that there is a value for the custom field […]", so checking if there is a value is ok. Furthermore, get_post_meta() is a simple wrapper for get_metadata(), which returns either an empty string '' or an empty array() if the value is not present. Can you please clarify your statement or do you need any help?
    – kaiser
    Feb 25, 2017 at 23:18
  • I wanted to make a note to reader, just that, nothing more... but the question title tells itself (i havent read the whole topic, just the title), that asked specific problem, and the answer is not 100% soolution to the problem I had (exactly as question ). Howevermaybe it was satisfying for OP.
    – T.Todua
    Feb 26, 2017 at 17:42
  • 1
    @T.Todua Then you have to clarify what you mean by "exists". As you can read in the answer as well as in the link I provided you in the comment above, get_metadata() is sufficient to check if the value exists in the DB.
    – kaiser
    Feb 26, 2017 at 18:09
  • 1
    Well, if you want the raw value, then you can use $id_list = [ /* your IDs */ ]; $wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE ".sanitize_key('post_id')." IN ($id_list) ORDER BY meta_id ASC", ARRAY_A );. Else, WordPress core will always return either an empty array or an empty string, depending on if you asked for a single value or all values via the functions argument.
    – kaiser
    Feb 26, 2017 at 21:16

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