WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Can't create an Images alt tag in The Loop (3 posts)

  1. made.of.legos
    Member
    Posted 6 years ago #

    Hello,

    I am having trouble dynamically creating an alt tag for an image while in the loop. I am pulling a posts custom field (where I have stored the url to the image) to create the <img> source. here is a snippet of code.

    // In The Loop
    ...
    <?php echo '<img class="thumb" src="'.get_post_meta($post->ID, 'post_image', TRUE).'"/>'; ?>
    ...

    This works to create the image. However, my "/" use for self cloing the <img> tag is stripped off.

    But, when I add something like this below it does not work.

    // In The Loop
    ...
    <?php echo '<img class="thumb" src="'.get_post_meta($post->ID, 'post_image', TRUE).'" alt="'.the_title().'" />'; ?>
    ...

    When the code executes, it places the info from the function the_title() in front of the <img> tag. My source looks like the following:

    text from the_title function<img class="pic" src="pictureURL" alt="" >
    `
    Hope someone can help me with this.

    Thanks

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    the_title() doesn't return the title, it echos it to the output itself.

    You can do either of two things:
    1. Use get_the_title() instead.
    2. Exit the PHP context instead of echo-ing a concatted string.. This usually is simpler to read.

    ...
    <img class="thumb" src="<?php echo get_post_meta($post->ID, 'post_image', TRUE); ?>" alt="<?php the_title() ?>" />
    ...
  3. made.of.legos
    Member
    Posted 6 years ago #

    Otto42,

    That worked perfectly. I truly appreciate all the help that you have sent my way.

    Take care

Topic Closed

This topic has been closed to new replies.

About this Topic