WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Script to show different image for different posts by their ID (2 posts)

  1. Pawel
    Member
    Posted 1 year ago #

    Hello!

    I am trying to create a short script that would show different image (within The Loop) for different posts by their ID. So should I create a post with ID 1 and create an image named "1.png", it would be displayed normally.

    But should I forgot to prepare an image or should user view a post that was published long time ago, it would display some random image (I think I will use image rotator for that but let's assume I will use "404.png").

    <?php
    if ( file_exists("<?php echo site_url(); ?>/images/post_images/<?php the_ID(); ?>.png") )
    {
    <img src="images/post_images/<?php the_ID(); ?>.png" alt="<?php the_title(); ?>" />
    }
    else
    {
    <img src="images/post_images/random/404.png" alt="<?php the_title(); ?>" />
    }
    ?>

    When I try to use this code I get a blank page. I guess there is something wrong with my syntax - in particular, I am not sure how should I connect WordPress-specific PHP code with strings (I don't know too much of PHP). Can anyone help me? :)

    I obviously want to include this code in index.php, not within the post content.

    Thanks in advance!

    [ Please do not bump, that's not permitted here. ]

  2. Pawel
    Member
    Posted 1 year ago #

    Got some guidance on another forum:

    <?php
    if(file_exists("images/post_images/".get_the_ID().".png"))
    {
    echo "<img src='images/post_images/".get_the_ID().".png' alt='".get_the_title()."' />";
    }
    else
    {
    echo "<img src='images/post_images/rotate/rotate.php' alt='".get_the_title()."' />";
    }
    ?>

    Problem solved!

Topic Closed

This topic has been closed to new replies.

About this Topic