Question

I have a custom field in WordPress called "thumb-url" which contains the exact location of an image. I want to only display the image if "thumb-url" contains the location of the image.

I'm start with an if statement that echoes photo exists if there's a value in the "thumb-url" custom field, otherwise it does nothing.

<div class="excerpt">
<?php
$key = 'thumb-url';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
echo 'photo exists';
}
?>

Now, here's the code that I really want the above if statement to echo if there's a value in "thumb-url":

<img alt="<?php the_title() ?>" src="<?php if ( function_exists('get_custom_field_value') ){ get_custom_field_value('thumb-url', true); } ?>" align="absmiddle" height="62" width="62" class="writtenpostimg" />

How do I get that ↑ inside the echo part of the if statement?

Much appreciated...

Was it helpful?

Solution

Assuming you're echoing it to the page for some sort of copy/paste instructions:

<div class="excerpt">
<?php
$key = 'thumb-url';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
    echo htmlspecialchars('<img alt="<?php the_title() ?>" src="<?php if ( function_exists(\'get_custom_field_value\') ){ get_custom_field_value(\'thumb-url\', true); } ?>" align="absmiddle" height="62" width="62" class="writtenpostimg" />');
}

?>

OTHER TIPS

This escapes the code... The other comment actually prints out "<img...>", so it depends on what you're trying to do.

You can remove the PHP tags and use conditional expressions:

<div class="excerpt">
<?php
$key = 'thumb-url';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
echo '<img alt="'.the_title().'" src="'.(function_exists('get_custom_field_value')?get_custom_field_value('thumb-url', true):'').'" align="absmiddle" height="62" width="62" class="writtenpostimg" />';

It might be easier to understand if you actually use a variable for it:

$url = ""
if(function_exists('get_custom_field_value'))
  $url = get_custom_field_value('thumb-url', true);
echo '<img alt="'.the_title().'" src="'.$url.'" align="absmiddle" height="62" width="62" class="writtenpostimg" />';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top