Show custom field if it exists, and show different elements if it doesn't

Basicly what I’m trying to do (with very basic knowledge of PHP):

If Custom Field $randomname exists for that particular post, show the content of that custom field.
If Custom Field $randomname doesn't exist for that particular post, show something else - for example: <div class="name">content</div>

Any help is highly appreciated.

Solutions Collecting From Web of "Show custom field if it exists, and show different elements if it doesn't"

Inside the loop, you can check the custom field with get_post_meta. Like this.

If custom field randomname exists then it will show it’s value otherwise it will print <div class="name">content</div>

<?php

    if ( get_post_meta( $post->ID, 'randomname', true ) ) {

        echo get_post_meta( $post->ID, 'randomname', true );

    } else {

        echo '<div class="name">content</div>';

    }

?>

OR you can use below which is shorter version of above using Ternary Operator

    echo get_post_meta( $post->ID, 'randomname', true ) ?  get_post_meta( $post->ID, 'randomname', true ) :  '<div class="name">content</div>';