• Hi,
    I want to add a conditional custom field to my posts (by adding to functions.php). I need to basically add a custom field to all posts automatically, if one hasn’t already been added.

    I found this code:

    <?php $songs = get_post_meta($post->ID, 'songs', true);
    /checking if anything exists for the key Songs
    if ($songs) { ?>
    Listening to: <?php echo $songs; ?>
    <?php } //if there is nothing for songs then display
    else { ?>
    Listening to: Nothing (Grooveshark is under maintenance)
    <?php } ?>

    I need to modify that however to add an “Image” custom field, how would I do that? Thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Not sure if I understand you correctly but you want to set a specific custom field value for the custom field key ‘Images’ to ALL existing posts? You probably need to use update_post_meta while looping over all your posts in a custom query.

    Nalin

    (@nalin_duminda)

    Try this

    <?php
    $songs = get_post_meta($post->ID, ‘songs’, true);
    //checking if anything exists for the key Songs
    if ($songs != ”) { ?>
    <img src=”<?php echo $songs;?>” />
    <?php } //if there is nothing for songs then display
    else { ?>
    <img src=”your default image path” />
    <?php } ?>

    Nalin

    (@nalin_duminda)

    or you you can try this in smart way. improve loading speed aswell.

    first create the image container
    <div class=”song_thumb”> </div>

    give your default image as background from css.

    and put this code within the div

    <?php
    $songs = get_post_meta($post->ID, ‘songs’, true);
    //checking if anything exists for the key Songs
    if ($songs != ”) { ?>
    <img src=”<?php echo $songs;?>” />
    <?php } ?>

    use this plugin to create image thumbnails for your post https://www.seoadsensethemes.com/wordpress-wp-post-thumbnail-plugin/

    Thread Starter futurepocket

    (@futurepocket)

    No no, I want to auto-add a custom field to all posts hereon ONLY if the custom field doesn’t already exist.

    E.g., If I forget to create a custom field called “Image”, then this function should automatically add a custom field called “Image” and auto-insert a default value (which I want to be able to define).

    I’ve checked out the code to auto-add custom fields within posts upon publish:

    add_action('publish_page', 'add_custom_field_automatically');
    add_action('publish_post', 'add_custom_field_automatically');
    function add_custom_field_automatically($post_ID) {
        global $wpdb;
        if(!wp_is_post_revision($post_ID)) {
            add_post_meta($post_ID, 'field-name', 'custom value', true);
        }
    }

    How would I add an IF command within that code to ONLY add the ‘field-name’ and ‘custom-value’ if one doesn’t exist already?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Conditional Custom Field’ is closed to new replies.