WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. parthatel
    Member
    Posted 6 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
    Member
    Posted 6 years ago #

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

  3. parthatel
    Member
    Posted 6 years ago #

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

  4. Dalton
    Member
    Posted 6 years ago #

    There's a plugin that makes this very easy:

    http://coffee2code.com/archives/2004/06/30/plugin-get-custom/

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

  5. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

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

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

    @Otto, the code doesn't work

  7. Chad_Coleman
    Member
    Posted 6 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. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    @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
    Member
    Posted 5 years ago #

    Good stuff,

    Thank you guys.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags