Support » Themes and Templates » Using an if exists statement with custom fields

  • I’m having trouble finding the proper wording/code to use a custom field if it exists.

    What I have is an href that I’d like to link to a custom field by the name of “source_url”. But If that custom field doesn’t exist, I’d like to link to the_permalink.

    So, if <?php get_post_meta($post->ID, ‘source_url’, true); ?> exists, echo that link, elseif echo <?php the_title(); ?>, in layman’s terms. 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • Use the post_custom field (it’s not documented in the Codex, yet). The following should work for what you want to do (no warranties).

    if (post_custom('source_url')) {
     // if the 'source_url' field exists, do this (output the source url)
     echo post_custom('source_url');
     } else {
     // otherwise, do this (output the post title)

    This goes a bit beyond the drop-in template tag structure for WP templates. The <?php and ?> is just a wrapper for PHP instructions, which are what all WP tags and functions are, so those aren’t needed if you’re calling WP template tags inside a larger function or such.

    Thanks scribblerguy!

    I changed the_title at the bottom to the_permalink and that did exactly what I was trying to figure out.

    Works like a charm. Cheers!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Using an if exists statement with custom fields’ is closed to new replies.