Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Help With PHP Echo Syntax
I just stumbled across another simple problem in my Wordpress site code :) I am trying to use an if/then function which will either echo one string of code or another.
Here is what I have right now:
<?php
if ( is_user_logged_in() ) {
echo '<a href="<?php echo wp_logout_url( home_url() ); ?>">Log Out</a>';
} else {
echo '<a href="http://example.com/wp-login.php">Sign In</a>';
} ?>
The echo string found in the "else" part of the function works just fine, because it is a plain url, however the the portion within the first echo isn't returning a plain url, but rather something like this: http://example.com/current-page/%3C php%20echo%20wp_logout_url(%20home_url()%20);%20?%3E.
I'm still new to php and I'm guessing that I'm not using the correct types of quotations or escape quotes or something. Any help would be greatly appreciated!
2 Answers
Keith Wolf
1,191 PointsGreat question. So the problem you're having is with the part inside the href attribute. This whole if/then statement is inside of the <?php tag at the top, so you don't need to add another <?php, it doesn't recognize that as code (so you're literally sending that code as text to the browser inside the link, which isn't what you want).
Instead do this:
echo '<a href="' . wp_logout_url( home_url() ) . '">Log Out</a>';
Notice that right after href=" there is a single quote. This is telling php to stop echoing text so we can add that URL. Then the next period says "add this next part to the echo". You add the logout_url, and another period saying "add this next text", another single quote, which starts echoing text again, and you continue.
Sorry for the laborious explanation but I hope it sort of helps. Copy/paste it into your text editor and play around with it. If I got it wrong let me know and I'll fix it.
Fantastic — works perfectly! Thanks for the detailed explanation too, I had no idea that you shouldn't use php within php in a case like this. I have seen examples of concatenation like this in php, but I still wasn't sure how to implement it and your answer clears it up perfectly.
Thanks!