I've noticed that my php inside of a WordPress site work without actually echoing some strings in specific situations.
Example:
<a href="<?php echo esc_url(the_permalink()); ?>">link</a>
<a href="<?php esc_url(the_permalink()); ?>">link</a>
Both code output the permalink on my wordpress website. (Versions: PHP 7.17, WP 4.9.8)
Question: When do I need to use echo and which security concerns do I need to be aware of?
Why both output the URL is because you are using the_permalink() - which echos the permalink. That in turn means it is NOT getting run through your esc_url
-
Instead, you need to use echo esc_url( get_the_permalink() );
- where get_the_permalink() does not echo, but returns - therefore it will get passed into esc_url
, which will then require the echo
The only difference between the_permalink
and get_the_permalink
: one echo's, one returns.
Note that WordPress is full of handy functions that work this same way:
the_ID() vs get_the_ID(),
the_title() vs get_the_title(),
etc...
Special case:
the_content() vs get_the_content()
Be aware however that the_content
, while naming follows the same pattern and does echo vs. return, the_content
has an additional difference that it passes the content through the the_content
filters (which does a lot of formatting, expands shortcodes, etc).