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:Can become:
So no: no need to store the result of
site_url()
in a variable each time.