I am confuse about get_the_*
and the_*
template tags. I have used those many times to my theme but i am not clear enough when to use get_the_*
and when to use the_*
. Would you please explain both concept clearly.
A template tag is a PHP function used to generate and display information dynamically. WordPress Themes contain different templates and theme developers use template tags to fetch and display dynamic data. WordPress has many built-in template tags that can be used in WordPress themes.
Building a WordPress Theme is so easy with template tags. You can add the_title() to display the post or page title, and you can use the_content() to display post or page contents. There are many more template tags in WordPress that we can use to display other things.
HTML <template> Tag.
Typically, there are two key differences between get_the_*
and the_*
functions.
get_the_*
methods don't echo anything themselves. Instead, they return the value that you're interested in, normally as a string. For example, get_the_time()
echoes nothing, and returns a string representation of the posting time of the current post. the_*
methods directly output the same value, without you having to echo it; the_time()
returns nothing, but directly echoes the posting time.
the_*
methods are generally designed to be used inside the Loop, so they often don't take a parameter to specify which post you're asking about; for example, the_title()
doesn't take a post_id
parameter, and can therefore only act on the "current" post inside the Loop. It doesn't make sense to call it outside the loop—which post would it be getting the title for? However, get_the_title()
takes a post ID as a parameter, so you can use it from anywhere to get the title of any post, as long as you've got the post's ID. (Many of the get_the_
methods take an optional post id parameter, and default to returning the value for the current post if they're used from in the Loop, for convenience.)
Because WordPress has been in development for so many years, and things have gradually been added, these aren't guaranteed rules, and you'll find exceptions here and there. You should take this as general advice and check the documentation for each specific instance as you need it.
The difference is that you can only use the_*
inside your loop. But get_the*
you can use inside or oustide the loop. Outside the loop you should give the post_id as a parameter.
And by default the_*
echo's the title for example and get_the*
just gets the title for using it in your PHP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With