Creating an "if exists" for custom field keys (9 posts)

  1. parthatel
    Posted 8 years ago #

    How do I create an "if" for the custom fields? For example, if my KEY ID is $example, how do I make it so that only content will only appear if the key $exampleis available.

    WordPress uses the

    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php endwhile; else: ?>
        <?php endif; ?>

    I've also seen:

    <?php if(function_exists('the_ratings')) { the_ratings(); } ?>

    So can't I make a

    <?php if(key_exists('$example')) {whatever i want here } ?>

  2. MichaelH
    Posted 8 years ago #

    Take a look at the code from the plugin, Redirectify for an example:

  3. parthatel
    Posted 8 years ago #

    Srry, I'm just a beginner at php. I still have no clue.

  4. Dalton Rooney
    Posted 8 years ago #

    There's a plugin that makes this very easy:


    Follow the instructions for adding it to your template, I think by default if there is no matching key, it outputs nothing.

  5. A plugin is not necessary, all that you need is built into WordPress.

    if (get_post_meta($wp_query->post->ID, $example_key, true) != '') {
  6. parthatel
    Posted 8 years ago #

    @Otto, the code doesn't work

  7. Chad_Coleman
    Posted 8 years ago #

    <?php if ( get_post_meta($post->ID, 'your_key_name', true) ) { ?>
    <?php echo get_post_meta($post->ID, "your_key_name", $single = true); ?>
    <?php } ?>

    Just swap out both instances of 'your_key_name'. Remember this belongs in the loop. And I always encourage you to read the WordPress Codex.

    A good example:

    <?php if ( get_post_meta($post->ID, 'header_image', true) ) { ?>
    <img src="<?php bloginfo('url'); ?>/wp-content/uploads/<?php the_time('Y/m'); ?>/<?php echo get_post_meta($post->ID, "header_image", $single = true); ?>" alt="<?php the_title(); ?>" />
    <?php } ?>
  8. @parthatel: Yes, it does. I use code like that all the time.

    Try it again, you messed up somewhere. The above code *works*.

  9. jzo
    Posted 8 years ago #

    Good stuff,

    Thank you guys.

Topic Closed

This topic has been closed to new replies.

About this Topic