WordPress.org

Ready to get started?Download WordPress

Forums

Adding Default Thumbnail (7 posts)

  1. stiwdio
    Member
    Posted 2 years ago #

    Wonder if someone to add to my code;

    I have a simple latest post in the sidebar, but have the an image, if saved in the custom field, for the post as the background of a div with rounded corners;

    It works well, but now I want to add a code to add a custom image if one isnt uploaded; Can someone help me out?

    Cheers

    <?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=1');
    while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
    <?php $post_back = get_post_meta($post->ID, 'homepage-thumbnail', $single = true);?>
    <div class="newsimage" style="background: url('<?php echo $post_back; ?>') no-repeat; background-size: 100%;"></div>
    <span class="sidetitle"><a href="<?php the_permalink() ?>" rel="bookmark"
        title="Link to <?php the_title(); ?>">
    <?php the_title(); ?></a> </span><br />
    <?php echo get_excerpt(150); ?>
    <?php endwhile;?>
    </div>
  2. Marco Milesi
    Member
    Posted 2 years ago #

    <?php if ( get_post_meta($post->ID, 'homepage-thumbnail', true) ) {?>
    <?php $post_back = get_post_meta($post->ID, 'homepage-thumbnail', $single = true);?>
    <?php endif; ?>

    Then use <?php } else {?> to add code for your custom images.

  3. stiwdio
    Member
    Posted 2 years ago #

    Hi Milmor

    Thanks for this, I haven't got a clue though could you show me exactly hwo I should write it?

  4. stiwdio
    Member
    Posted 2 years ago #

    Maybe I should add this is in the sidebar

    Please can someone help me

  5. Marco Milesi
    Member
    Posted 2 years ago #

    Try with this:

    <?php
    if ( get_post_meta($post->ID, 'homepage-thumbnail', true) ) {
    $post_back = get_post_meta($post->ID, 'homepage-thumbnail', $single = true);
    echo '<div class="newsimage" style="background: url(' . $post_back . ') no-repeat; background-size: 100%;"></div>';
    } else {
    echo '<div class="newsimage" style="background: url(yourhttpimagepath) no-repeat; background-size: 100%;"></div>';
    }
    ?>

    You have to replace "yourhttpimagepath" with the alternative image

  6. prionkor
    Member
    Posted 2 years ago #

  7. stiwdio
    Member
    Posted 2 years ago #

    Thank you Milmor
    That worked well;

Topic Closed

This topic has been closed to new replies.

About this Topic