PHP echo easy problem ;) - php

Ok, it's Wordpress related and I know about Wordpress Stack Exchange, but I'm asking here because this is mostly a PHP question.
I want my code to display something or nothing using if statement.
The problem is I'm going to have a variable and bloginfo('template_directory') in-bulit function.
I wrote this:
<?php if (!empty($instance['example']))
echo "<li><img src="?><?php bloginfo('template_directory') ?><?php echo "/images/example.png /></li>"; ?>
It works fine until $instance['example'] is not empty, when is - it still displays the template directory link including images/example.png.
Any ideas?
I've tried " . bloginfo('template_directory') . " but doesn't seem to work.

PHP if statements that do not have braces { } will only evaluate the first line thereafter. To resolve this,
<?php if (!empty($instance['example'])) {
echo "<li><img src="?><?php bloginfo('template_directory') ?><?php echo "/images/example.png /></li>"; } ?>
Try that and see if it works for your needs. All I did was insert the braces so that your if statement spans all of your arguments.

You forgot to add the : after the if statement to make an if endif; block. Alternatively use the standard curly brackets to enclose all your commands in the if statement.
Currently it's only checking if for the first echo command.

Try this code:
<?php if (!empty($instance['example']))
echo "<li><img src=".get_bloginfo('template_directory')."/images/example.png /></li>";
?>

Try this
<?php if (!empty($instance['example'])) {
echo "<li><a href=". $example ."><img src="?><?php bloginfo('template_directory') ?>
<?php echo "/images/example.png /></a></li>";
}
?>

I'd personally use.
<?php
if( !empty( $instance['example'] ) )
echo '<li><img src="' . get_bloginfo('stylesheet_directory') . '/images/example.png" alt="" border="0" /></li>';
?>
First we add those missing attribute quotes.
Second we use the stylesheet path to ensure it points to the correct location for a child theme.
Third we call get_bloginfo to get a return value for the echo statement.
Fourth, i also added a border="0" to the image, borders aren't usually wanted for an image inside a link and also added an alt tag, because it will at least help pass HTML validation, even if you leave it empty.

Same answer as others, but with better formatted code:
<?php
if(!empty($instance['example']))
{
echo '<li><a href=' . $example . '><img src=' . bloginfo('template_directory') . '/images/example.png /></a></li>';
}
?>
Added brackets, removed unnecessary opening/closing php tags, and converted strings to single quotes since there are no variables or special characters contained within them that need processing.

Related

Included php tag in html attribute

How do I include a php tag in an HTML attribute? I still find it quite tricky.
This is the HTML attribute:
src="https://customer.site.com/?language=en_US&portal=Default"
The thing is, ?language should accept a dynamic value. That value is stored in $lingos[$wmpl_langcode].
So I've been trying many variations and I'm still stuck.
I've got this now but it doesn't seem right.
src=<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
I don't want to waste any more time on it. Any tips would be great.
you was just missing one double quote and the ; at the end of the echo to end the instruction:
src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode]; ?>&portal=Default"
You are now missing quotes for the attribute.
This however would be perfectly fine:
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"
If you like it a bit more clean without confusing quotes:
<img src="https://customer.site.com/?language=<?php echo $lingos[$wmpl_langcode] ?>&portal=Default"/>
You should also think about urlencode():
<img src="https://customer.site.com/?language=<?php echo urlencode($lingos[$wmpl_langcode]) ?>&portal=Default"/>
To make it "more clean", you should use a templating engine.
When you directly use echo to print the dynamic link, the quotes are not present there.
Try this:
src="https://customer.site.com/?language=<?=$lingos[$wmpl_langcode] ?>&portal=Default"
OR
src="<?php echo "https://customer.site.com/?language=" . $lingos[$wmpl_langcode] . "&portal=Default" ?>"

Echoing PHP within HTML

I am currently trying to create a shopping cart for my website and I have images of products stored in a database and I want to include them within <img src> . By putting $get_row[imagesrc] within the src. I need to know the correct way to add it to the below code as I dont fully understand the ' and . tags
echo '<p>'.$get_row['name'].'<br/>'.$get_row['description'].'<br/>'.$get_row['imagesrc'].
'<br/>£'.number_format($get_row['price'],2).'Add</p>';
This should achieve what you're looking for:
echo '<p>'.$get_row['name'].'<br/>'.$get_row['description'].'<br/><img src="'.$get_row['imagesrc'].'" /><br/>£'.number_format($get_row['price'],2).'Add</p>';
The ' character defines a string literal when it is wrapped around a series of characters.
The . character is used for concatenating strings for output or storage.
echo '<p>'.$get_row['name'].'<br/>'.$get_row['description'].'<br/><img src="'.$get_row['imagesrc'].'"><br/>£'.number_format($get_row['price'],2).'Add</p>';
. concatenates two strings, and ' is wrapped around a string.
so
echo 'Hello '.'World'; // Shows Hello World
I'd split yours up to make it easier to read:
echo '<p>';
echo $get_row['name'].'<br/>';
echo $get_row['description'].'<br/>';
echo '<img src="'.$get_row['imagesrc'].'" /><br/>';
echo '£'.number_format($get_row['price'],2);
echo 'Add';
echo '</p>';
But it all looks OK.
echo '<p>'.$get_row['name'].'<br/>
<img src="'.$get_row['imagesrc'].'" alt="'.$get_row['name'].'"><br/>
<br/>£'.number_format($get_row['price'],2).'
Add</p>';`
echo '<img src="'.$get_row['imagesrc'].'">';
Try that.
A specific answer has been given:
echo '<img src="'.$get_row['imagesrc'].'">';
Nonetheless, it's worth adding that you should:
You should escape output - with htmlspecialchars() or otherwise.
echo '<img src="' . htmlspecialchars($get_row['imagesrc']) . '">';
Read the documentation on PHP Strings.
Check out this way of including PHP in your HTML. It's much easier to read and maintain. The last line in the paragraph is your image tag.
<p>
<?php echo $get_row['name']; ?><br/>
<?php echo $get_row['description']; ?><br/>
<?php echo $get_row['imagesrc']; ?><br/>
£<?php echo number_format($get_row['price'],2); ?>
Add
<img src="<?php echo $get_row['imagesrc']; ?>" />
</p>

IMG SRC Using Path from MySQL and PHP

I have the following line of code which doesn't seem to be working:
echo "<img src='/images/albumart'"; echo $row['art1']; echo "/>";
The 'art1' is definitely returning '/imagename.png' so the URL should be complete however nothing being displayed.
Any ideas?
Thanks.
You really should be concatenating that string:
<?php
echo '<img src="/images/albumart'.$row['art1'].'"/>';
?>
and ideally break out of php to do this:
<img src="/images/albumart<?php echo $row['art1']; ?>"/>
If you're not familiar, the period in php joins strings. That's called concatenation. No need to echo little bits like that, in fact please never do it the way you demonstrate. The root of your issue is, as Geoff pointed out, you weren't closing the src param.
echo "<img src='/images/albumart'"; echo $row['art1']; echo "/>";
It looks like you are closing the img src paramter after the albumart part.,
try this:
echo "<img src='/images/albumart"; echo $row['art1']; echo "' />";

Adding A Dynamic Link In Php

I have been using the following to add a dynamic link on a page I am writing, it works ok and appears how it should on the page but I cant help but think that I am going a bit backwards with the way its written as it looks messy. What is the correct way to write it, as if I put it all in one line it doesn't work ?..
echo '<a href="./customer-files/';
echo $customerID;
echo '/';
echo $filename->getFilename();
echo '">';
echo $filename->getFilename();
echo '</a>';
Try with
echo "{$filename->getFilename()}";
Here there is the documentation with a lot of examples of how to concatenate output.
I'd approach it like this:
$safe_customer_id = htmlspecialchars(urlencode($customerID));
$safe_filename = htmlspecialchars(urlencode($filename->getFilename()));
$safe_label = htmlspecialchars($filename->getFilename());
echo "$safe_label";
I would go with this:
$fn = $filename->getFilename();
$link = $customerID . '/' . $fn;
echo ''.$fn.'';
If you're using a template layer, it is even better to break out into PHP only when you need to:
<a href="./customer-files/<?php
echo $customerID . '/' . $filename->getFilename()
?>">
<?php echo $filename->getFilename() ?>
</a>
This way, your IDE will correctly highlight your HTML as well as your PHP. I've also ensured that all PHP is in single-line blobs, which is the best approach for templates (lengthy statements should be banished to a controller/script).
Concatenation is your friend. Use a . to combine multiple string expression into one.
echo ''.$filename->getFilename()/'';
Even better way would be
$filename = $filename -> getFilename(); //cache the filename
echo "<a href='/$customerId/$filename'>$filename</a>";
// ^ On this echo NOTICE that variables can be DIRECTLY placed inside Double qoutes.

My php variables are not being printed out.

<?php if ( is_user_logged_in() ) {
echo '<img id="visit-the-forums" src="<?php bloginfo('template_url') ?>/images/visit-the-forums.png" alt="Check out the Forums!" />'
} else {
echo '<img id="join-the-forums" src="<?php bloginfo('template_url') ?>/images/join-the-forums.png" alt="Join the Forums!" />'
}
?>
I think there is something wrong w/ the way I set up the "php bloginfo" code inside but I'm not sure how to fix it.
The code below should work for you. You had to make use of string concatenation:
<?php if ( is_user_logged_in() ) {
echo '<img id="visit-the-forums" src="' . bloginfo('template_url'). '/images/visit-the-forums.png" alt="Check out the Forums!" />'
} else {
echo '<img id="join-the-forums" src="' . bloginfo('template_url') . '/images/join-the-forums.png" alt="Join the Forums!" />'
}
?>
You have 2 problems:
Most likely this code is not
executing because you're echoing a
string that's delimited with single
quotes and inside it you've put
unescaped single quotes. (You can tell this is the case because even on this page, the syntax colouring is messed up :)
Even if you had escaped the single
quotes (e.g. <?php
bloginfo(\'template_url\') ?>) this
would not work because you're using
PHP to echo PHP code, which will then
be passed to the browser, instead of
being executed by the PHP engine.
What you need to do is to add the result of bloginfo() (or get_bloginfo(), see edit below) to the string you're outputting:
echo '<img id="visit-the-forums" src="'. bloginfo('template_url') . '/images/visit-the-forums.png" alt="Check out the Forums!" />'
(note the correct usage of single-quotes as delimiters, and the correct syntax highlighting on this page: strings are reddish, code is black)
EDIT: if bloginfo here is the WordPress function, you will want to replace it in my code above with get_bloginfo which actually returns the result rather than printing it, but your original question wasn't clear about what bloginfo is/does.

Categories