WordPress.org

Ready to get started?Download WordPress

Forums

Using an if exists statement with custom fields (3 posts)

  1. jimmiejo
    Member
    Posted 6 years ago #

    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. :)

  2. scribblerguy
    Member
    Posted 6 years ago #

    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).

    <?php
    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)
     the_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.

  3. jimmiejo
    Member
    Posted 6 years ago #

    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!

Topic Closed

This topic has been closed to new replies.

About this Topic