• parthatel

    (@parthatel)


    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 } ?>

Viewing 8 replies - 1 through 8 (of 8 total)
  • MichaelH

    (@michaelh)

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

    Thread Starter parthatel

    (@parthatel)

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

    Dalton Rooney

    (@daltonrooney)

    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.

    Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    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
    }
    Thread Starter parthatel

    (@parthatel)

    @otto, the code doesn’t work

    chad_coleman

    (@chad_coleman)

    <?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 } ?>
    Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    @parthatel: Yes, it does. I use code like that all the time.

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

    Good stuff,

    Thank you guys.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Creating an “if exists” for custom field keys’ is closed to new replies.