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.
问题:
回答1:
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 apost_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 theget_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.
回答2:
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.