I've noticed that my php inside of a WordPress site work without actually echoing some strings in specific situations.
Example:
link
link
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).
According to the official source the function the_permalink() Displays the permalink for the current post.
So it has built-in functionality to print output without echo so you can use whatever text you like as the link text, in this case, “permalink”.
permalink
Echo
The echo() function outputs one or more strings.
echo is not actually a function (it is a language construct), so you
are not required to use parentheses with it. echo (unlike some other
language constructs) does not behave like a function, so it cannot
always be used in the context of a function. Additionally, if you want
to pass more than one parameter to echo, the parameters must not be
enclosed within parentheses.
Related
For a long time now, I have had my own wrapper function around echo, so that instead of:
echo 'This is an example.';
I do (in CLI scripts):
terminal_output('This is an example.');
This allows me to, for example, do fancy outputting of the text on the terminal. For example, I can make it look like it's "typed out" with random delays.
Sometimes, I realize that I have been using "echo" instead of my wrapper function, and then I have to sit and change them all into my function calls.
It strikes me that, maybe, there is some way to "hook into" the echo function so that I can indeed use echo everywhere, yet do any kind of fancy processing I feel like? And of course, that wrapper function would check whether it's in web or cli mode, and always directly output if in web mode.
I've oftentimes found hidden "gems" like this in PHP which are barely documented or well hidden, so maybe it's the case this time as well?
Functions can be namespaced. PHP native functions can be redefined with the same name in custom namespaces.
But echo is a special case. It is not a function, but is a language construct.
// echo supports non-function-shape calls since it's a language construct.
echo "string", "string";
AKAIK, the language may not allow you to define a function with that name.
My code editor has a build in snippet for echo that looks like this:
echo($var);
All the snippets that I browse on the internet are formated without parentheses. Like this:
echo $var;
What is the difference? Which one is correct or considered as a better practice?
echo is not actually a function (it is a language construct), so you are not required to use parentheses with it. echo (unlike some other language constructs) does not behave like a function, so it cannot always be used in the context of a function. Additionally, if you want to pass more than one parameter to echo, the parameters must not be enclosed within parentheses.
Going through the documentation , you can notice, that is not a problem, but really unnecessary and I believe your code editor have some setting, you may like to change to get it normal .
I've run into a little bit of a snag with shortcodes. I want it to take the variable and put it in place for the text that should usually go there, but instead of working it just doesn't load it up, even though I've tested it with the echo to see if it's putting anything out and it is.
<?php
$artistslug = the_field('artist_cat_slug');
echo $artistslug; // Here for test reasons
echo do_shortcode('[product_category category="'.$artistslug.'"]');
?>
Any help would be greatly appreciated.
Most probably, the_field() displays the value. The plugin you are using might have a corresponding function to return the value instead, for e.g. get_the_field(). Use that instead.
Edit after clarification in comments
From the documentation for the_field() (emphasis mine):
Displays the value of the specified field. (this is the same as echo get_field($field_name))
Exactly. Use get_field() instead.
I have very basic pagination script and search form with ~4 fields, and action="get" now my problem is that, when i submit my form, i get url like this:
user/people/1/?search=true&country=uk&age=20&online=true ... and so on
so after i submit form everything is just fine, but when i go to page 2 my url changes to:
user/people/2
so my search parameters disappears, this is how i render my links
href="user/people/<?=$next?>"
So my question is what is the best way to keep my paramenters, because now i can only think of for loop and build my link by merging all $_GET values, should i do it like that?
Just append $_SERVER[ 'QUERY_STRING' ] (make sure to htmlspecialchars() it first).
href="user/people/<?php echo htmlspecialchars( "{$next}?{$_SERVER[ 'QUERY_STRING' ]}" ); ?>"
By the way, the PHP short tags <?= ?> are not portable, so you should consider not using those, and using <?php echo ?> instead.
Update:
#Wrikken raises a couple of good points in their answer:
1) passing ENT_QUOTES as the second argument to htmlspecialchars() would be important if single-quoting the attribute value (or to cover it being changed to being single-quoted in the future). This is easy to forget, for me anyway, since I almost always double-quote attribute values. It's unfortunate that it further bloats a call that's already bloated by a long function name.
2) If you're just passing through the query string as-is, then I'd certainly prefer using $_SERVER[ 'QUERY_STRING' ] instead of http_build_query( $_GET ). If, however, you need to change some of the query params, http_build_query() would be the ticket. You can see an example of that in my PHP faceted browser.
Either:
...ople/?<?php echo htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES);?>"
Or:
...ople/?<?php echo htmlspecialchars(http_build_query($_GET), ENT_QUOTES);?>"
Or:
...ople/?<?php echo htmlspecialchars(http_build_query($some_custom_array), ENT_QUOTES);?>"
I am new to programming and learning with Wordpress.
the_title(); //outputs the title of the page
I want to capture the title of the page into a string variable so I can manipulate it with strtolower and str_replace functions.
The only way I have gotten it to work is with output buffering.
ob_start();
the_title();
$result = ob_get_clean();
echo str_replace(" ","-",strtolower($result));
/*there has got to be an easier way....
i dont fully understand why */
str_replace(" ","-",strtolower(the_title()));
What am I doing wrong?
If what you really are looking for is the wp_title function, the 2nd argument it takes is a boolean on whether or not it should display it or return it. Pass it false so it will return it to the var, then you can do this:
$mytitle = wp_title(null, false);
Otherwise, your only option is to find the function you're looking for and modify the source code.
There is no easier way. Your function does not return the string, it prints it, therefore you will have to use output buffering if you want to capture the output.
It's the difference between f1() and f2() in the following example.
// Returns a string, prints nothing.
function f1() {
return "String";
}
// Prints a string, returns nothing.
function f2() {
echo "String";
}
Wordpress is a HORRIBLE app to learn how to program from. It uses these global functions that "just work" but they do very specific tasks "inside 'The Loop'". As I say, this is a horrible example of what good code should be.
Thankfully (for you) there are other functions that just return the part you're looking for. Rather than me just writing what you need, you can read a full listing here. Take care that you note down which must be within the mythical Loop and which you can use anywhere.
As it happens there are even more ways to get the title, but I was really imagining for this example you would do something like:
$this_post = get_post($post); // I *think* $post is the post ID inside the loop though I could be wrong
echo $this_post->post_title;
But as another poster (correctly) says you can use a fairly simple wp_title() function to grab the current loop title.
This brings me back to perhaps wanting to explain why learning programming from Wordpress is a bad idea. They have so many damned way of doing the same damned thing that it's almost impossible to keep on top of things.
A blog is a really simple set of data (even moreso in WP's case because it isn't fully normalised) but rather than just having one way to output a title <?php echo $post->title; ?> you have umpteen ways, all doing subtly different things.
If you really want to learn how to program (instead of hacking your way around the crap that is the WP internals), creating a simple blog engine is fairly quick and fun... It's certainly how a lot of people get into a new language or framework.
And if you really want to have fun, have a look at Django.
Enough of the Wordpress rant. If you're fighting something like this in the future that doesn't have 100 ways of doing it, I really wouldn't recommend output-buffer-capturing. It uses up a whole buttload of resources for something relatively simple.
The easiest way can be as simple as just taking the source for the original function, sticking it in a new function and replacing the echo with return.
Just note there may be some database connectivity to handle that returning prematurely may break... So if the echo isn't the last statement, instead of returning right there, store the string as a variable and return at the end of the function.
just figured Id share my final solution with you guys.
This was to give my body tags unique id's in wordpress.*/
$title =wp_title(null,false);
echo strtolower(str_replace(' ','-',ltrim($title)));
//without the ltrim() 2 dashes are created before the title.
Almost every 'the_*' function in Wordpress has a 'get_the_*' counterpart. So, you just have to use
echo str_replace(" ","-",get_the_title());
And it's going to work like a charm. there's also get_the_excerpt(), get_the_content() and the_permalink() which somehow breaks the naming convention (God knows how many times I've written "get_the_permalink()" and got frustrated on why it didn't work)
Cheers!