Here are two examples of what I'm referring to.
If I wanted to make an array containing images and echo it out later, and have the images refer to the home directory, I could do the following:
<?php
$get_directory = site_url();
$random = rand(0, 1);
$picture = array(
$get_directory.'/images/0.jpg',
$get_directory.'/images/1.jpg',
);
?>
And call it:
<img src="<?php echo $picture[$random];?>"></a>
I put site_url() in the $get_directory variable and it worked properly. Before I did that, I tried inserting the function directly into the array and it didn't work.
Another example that I found recently, involving echoing with a string:
<?php
$thumbnail = get_post_meta($post->ID, $img, $single = true);
$get_directory = site_url();
if (!$thumbnail) {
echo ''; } else {
echo '<img src="'.$get_directory.'/wp-content/uploads/'.$thumbnail.'">'; ?>
I needed to put the home directory site_url() function and the get_post_meta() function into variables to properly echo them out, put them in an array, or concatenate them.
I'm wondering if this is the correct way and if functions always need to be placed into variables, or if there's a correct way to do it.
I apologize in advance if this question is inappropriate or has already been asked and answered. I looked and did not find my exact question. I'm very new to the programming aspect of web development. Thank you.
site_url() takes a parameter ($path). This parameter will be appended to the site URL:
echo '<img src="'.$get_directory.'/wp-content/uploads/'.$thumbnail.'">';
Can become:
echo '<img src="' . site_url('/wp-content/uploads/' . $thumbnail) . '">';
So no: no need to store the result of site_url() in a variable each time.
Related
I'm trying to setup my WordPress website so that if a post / page has a featured image assigned, this image will be used as the page banner. If however the page doesn't have a featured image, it must onload select a random image out of six available options. I've tried to used this if statement below:
<div id="slider">
<div class="theslide">
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6); '.jpg">';
}
?>
</div>
</div>
It works, but the random number function is not closing preperly, so the code ends up looking like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6 </div>
</div>
</div>
Instead of like this:
<div id="slider">
<div class="theslide">
<img src="/wp-content/uploads/link-ship-chandlers-banner-6.jpg">
</div>
</div>
I'm assuming my syntax is wrong for using php inside of the echo, but everything I try either has the same problem or cause a php error.
Any help would be appreciated.
Thanks in advance
Willem
If you don't need to know which header was chosen, just do this:
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';
Using more than one ; on a line is a no-go (you are essentially telling the php-interpreter that '.jpg">'; is an independant command - which will do nothing)
Assigning a variable (ie. $whatever = 'something) inside the echo statement won't be a problem in this case - though it really doesn't do any good either. What it does is create a new variable called $random that you could use afterwards to find out which header was used - but results will be unpredictable if used in the echo statement (ie. in your case the variable would contain [random number].jpg, not just the random number), instead assign the random number to $random first like this:
$random = rand(1,6);
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random . '.jpg">';
echo "We are using header {$random}, which was chosen at random.";
Note that the above example also shows an alternate way to include the variable in a string - using double-quotes you can simply write the variable directly inside the string itself. When doing so I recommend always using {} to wrap the variable though not needed in this case - this allows referencing more complex variables (such as array elements or object properties), and it makes the whole thing more readable too.
Other (IMO less readable, possibly more error-prone) solutions include:
$random = rand(1,6);
echo "<img src=\"/wp-content/uploads/link-ship-chandlers-banner-$random.jpg\">";
echo sprintf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
printf('<img src="/wp-content/uploads/link-ship-chandlers-banner-%d.jpg">', $random);
Actually this can work, but you end the line with ;.
So removing the ; and adding a .
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . $random = rand(1,6) . '.jpg">';
do this alternatively you don't need to set this variable
echo '<img src="/wp-content/uploads/link-ship-chandlers-banner-' . rand(1,6) . '.jpg">';
I need to store a hyperlinked image inside a variable, and then echo out that variable for my WordPress website. I find it more convenient to use bloginfo('template_directory') so that I can go back and forth between local and live server.
But bloginfo('template_directory') within a variable does not work, it displays nothing. But bloginfo('template_directory') will work in other areas of my website. What could be the problem?
CODE A works. Notice 127.0.0.1 in the URL
<?php
$var = '<a href="http://www.twitter.com">
<img src="http://127.0.0.1/wp-content/themes/twentyfourteen/images/social/twitter.png" />
</a>';
echo $var;
?>
CODE B displays nothing. Why is the below not working? Notice below I am using bloginfo('template_directory') instead of 127.0.0.1
<?php
$var = '<a href="http://www.twitter.com">
<img src="<?php bloginfo('template_directory'); ?>/images/social/twitter.png" />
</a>';
echo $var;
?>
EDIT
CODE C how to replace the word "twitter" with a variable? (I am referring to line 3 below, the word "twitter" that is located in img src)
<?php
$var = '<a href="http://www.website.com">
<img src="' . get_bloginfo("template_directory") . '/images/social/twitter.png" />
</a>';
echo $var;
?>
You need to use get_bloginfo for you want it in a var. Also no need for php tags when in a string.
http://codex.wordpress.org/Function_Reference/get_bloginfo
<?php
$var = '<img src="'. get_bloginfo('template_directory') .'/images/social/twitter.png" />';
echo $var;
?>
Also also suggest using something like this instead for child themes.
http://codex.wordpress.org/Function_Reference/get_template_directory_uri
<?php
$var = '<img class="svg " src="'. get_template_directory_uri() .'/images/social/twitter.png">'
echo $var;
?>
In response to your EDIT C code block, I'm guessing you are trying to loop through some social media icon links. This is how you might do that:
<?php
// Array of social sites
$sites = array(
'twitter',
'facebook',
'instagram'
);
// Loop through each
foreach($sites as $site){
$var = '<img src="'. get_template_directory_uri() .'/images/social/'. $site .'.png">';
echo $var;
}
?>
Don't use get_bloginfo( 'template_directory' ) and for that matter get_bloginfo( 'stylesheet_directory' ) which is used for child themes. These was used in early Wordpress versions. In later versions these was "replaced" with more appropriate functions.
The correct functions to use is get_template_directory_uri() for parent themes and get_stylesheet_directory_uri() for child themes. I would suggest that you work through these pages carefully
As for your syntax, as explained in the other answer, you cannot use HTML and PHP in the same string without separating them. This is done using the string operators which you can go and read up on in the link provided
It seems that you need to add social media icons. If so, check out these two posts. Specially read the one that #toscho done to my question. That should help you quite a lot with a few issues
listing repeating social media buttons. Take your time on this one. This is an excellent post that helped me out big time when I just started out
Social share buttons using genericons
You can't have PHP tags in PHP tags:
Just concatenate the strings:
<?php
$var = '<a href="http://www.twitter.com">
<img src="' . get_bloginfo("template_directory") . '/images/social/twitter.png" />
</a>'; //↑ ↑ See here
echo $var;
?>
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.
what I want to do is want to save php variable in database (suppose {$baseUrl} ) and I am getting the data on php page with echo command and on the same page I have defined $baseUrl='/public'. I want to get the value for the base url but I'm getting simply {$baseUrl} not '/public'
in db I have <img src="{$baseUrl}/img.jpg" />
on page I have
$baseUrl = "/public";
echo $content
it is giving <img src="{$baseUrl}/img.jpg /">
how can I get <img src="/public/img.jpg" />
Of course. Strings are strings, not PHP code. You'll have to replace it yourself, e.g.:
<?php
$baseUrl = '/public';
$string = '<img src="{$baseUrl}/img.jpg" />';
$replacements = array(
'{$baseUrl}' => $baseUrl,
);
echo strtr($string, $replacements);
I think what you want to do is a string replace. The variable pointer ($baseUrl) is a string that comes from the database. If you echo it, it is still just a string. What you need to do is something like this:
<?php
echo str_replace('$baseUrl', $baseUrl, $varFromDB);
?>
Or do I understand your question wrong?
With
str_replace($content, '{$baseUrl}', $baseUrl)
.
I am guessing that you are using the wrong quotes:
echo '<img src="{$baseURL}/img.jpg" />';
rather than
echo "<img src='{$baseURL}/img.jpg'/>";
You want the $baseUrl variable to be evaluated? You have to put the variable outside of the string definition:
echo '<img src="' . $baseUrl . '/img.jpg" />';
or put it between double quotes (strings enclosed in double quotes are parsed by PHP):
echo "<img src=\"{$baseUrl}/img.jpg\" />";
Based on your comments, you need this solution:
$content = str_replace("{$baseUrl}", $baseUrl, $content);
You may want to use the eval() function...
This is not a good idea, but it would achieve what you want.
I am printing an image using an ID which is generated. however i wanted to do a check to see if this image exists and if it doesnt print no-image.jpg instead...
<img src="phpThumb/phpThumb.php?src=../public/images/'.$row["id"].'/th.jpg&w=162" alt="" width="162" />
It would be great if this could be kept on one line is possible. Any help would be appreciated.
What Kristopher Ives says, and file_exists:
echo (file_exists("/path/file/name/here") ? "web/path/goes/here" : "no_image.jpg")
btw, your snippet is unlikely to work, as you seem to be combining plain HTML output and PHP without putting the PHP into <? ?>
My recommendation would actually be to abstract the decision making from the html tag itself, in a separate block of php logic that is not outputting html...here is an abbreviated example that assumes you are not using a template engine, or MVC framework.
<?php
$filename = 'th.jpg';
$filePath = '/public/images/' . $row['id'] '/';
$webPath = '/images/' . $row['id'] . '/';
//Logic to get the row id etc
if (!file_exists($filePath . $filename)) {
$filename ='no-image.jpg';
$webPath = '/images/';
}
?>
<img src="<?php echo $webpath . $filename;?>" />
Wow, this question gets asked and answered a lot:
http://en.wikipedia.org/wiki/Ternary_operation
You could do it by:
<img src="<?php ($row['id'] != 0) ? "../public/{$row['id']}.jpeg" : 'no_image.jpg'; ?> >