Forums

Need Simple PHP Code (6 posts)

  1. gsweb
    Member
    Posted 2 years ago #

    Right now I use WP Post Thumbnail (plugin) and the following code to pull up images:
    <img src="<?php echo get_post_meta($post->ID, 'pft_square', true); ?>" alt="<?php the_title(); ?>" class="img" />

    I need a code which will pull up not only pft_square but pft_widescreen and pft_rectangle also. Only one image will be displayed for each post, so it needs to also recognize when no thumbnail is given if possible.

  2. stvwlf
    Member
    Posted 2 years ago #

    how is it supposed to work, that the first image found of the 3 possible images is the one displayed, checking in the order you specified?

  3. gsweb
    Member
    Posted 2 years ago #

    The order doesn't matter, as long as it only displays one of the images.

  4. stvwlf
    Member
    Posted 2 years ago #

    Try this code (didn't test it). It reads 1st custom field. If its empty or not existing it reads second, if 2nd empty or not existing reads 3rd.
    When a value has been stored to the variable (meaning it found a custom field) it displays the image it found. If none found no image is displayed.

    <?php
    $src = get_post_meta($post->ID, 'pft_square', true);
    if (!$src) get_post_meta($post->ID, 'pft_widescreen', true);
    if (!$src) get_post_meta($post->ID, 'pft_rectangle', true);
    if ($src) { ?>
       <img src="<?php echo $src); ?>" alt="<?php the_title(); ?>" class="img" />
    <?php } ?>
  5. jonimueller
    Member
    Posted 2 years ago #

    I bet the plugin author would give you some help. Have you tried asking or dropping a comment on the plugin's page? That's a pretty nifty plugin, BTW.

  6. Mark / t31os
    Moderator
    Posted 2 years ago #

    stvwlf, slight error mate in what you post...

    These 2 lines...

    if (!$src) get_post_meta($post->ID, 'pft_widescreen', true);
    if (!$src) get_post_meta($post->ID, 'pft_rectangle', true);

    ... i believe should be..

    if (!$src) $src = get_post_meta($post->ID, 'pft_widescreen', true);
    if (!$src) $src = get_post_meta($post->ID, 'pft_rectangle', true);

    Ternary equivalent... (for the sake of doing the same, another way..)

    <?php
    $src = (get_post_meta($post->ID, 'pft_square', true)) ? get_post_meta($post->ID, 'pft_square', true) : false;
    $src = (!$src && get_post_meta($post->ID, 'pft_widescreen', true)) ? get_post_meta($post->ID, 'pft_widescreen', true) : false;
    $src = (!$src && get_post_meta($post->ID, 'pft_rectangle', true)) ? get_post_meta($post->ID, 'pft_rectangle', true) : '/path/to/default/image.jpg';
    ?>
    <img src="<?php echo $src); ?>" alt="<?php the_title(); ?>" class="img" />

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags