WordPress

WordPress Functions that Echo vs Functions that don’t Echo

Reading Time: < 1 minute

When you first start working with WordPress functions, you quickly realize that there are some functions that automatically echo (print out) the results vs. returning the results.

In this post, we’ll look at how to tell if WordPress echo’s the results of a function or returns a value to the caller? And under what use cases do we use each type.

I can’t tell you how many times I’ve accidentally used echo like the following:

echo the_content();

When in reality all you need to do is execute the statement without the echo:

the_content();

If I truly wanted to manually do this I would use get_the_content() instead of the_content() like the following:

echo get_the_content();

However, you should be careful when using get_the_content(), because get_the_content() does not pass the content through the normal the_content filter(s), which means that it will not auto-embed videos or expand shortcodes, etc.

You will find that several WordPress functions have an echo version and a non-echo version of the code. There are plenty of use cases for both just remember the following:

  • The echo versions often do a lot of additional processing or formatting for you.
  • In general, when your goal is to output (echo) the results as finished HTML you should use the function without the get_
  • get_ : means it will return a value to you (not output / echo it).

Other examples of echo vs. non-echo functions:

the_title(); // echos the title
$title = get_the_title(); // returns the title

the_ID(); // echos the ID
$id = get_the_ID() // gets the id

// do
$parentId = wp_get_post_parent_id(get_the_ID());

// don't do
$parentId = wp_get_post_parent_id(the_ID());

the_id() does the following (which is not what you’d want to do in the example above):

function the_ID() {
   echo get_the_ID();
}

Join the discussion

  1. BrianGap

    I value the info on your web site. Much thanks!

Comments are now closed.