Skip to content
Advertisement

why is WordPress printing my array instead of just constructing it?

I am trying to apply a custom view to all the results of a visit to a taxonomy page, which involves wrapping the whole lot of results in some DOM boilerplate and then invoking the function to display each result as an element within that boilerplate. My strategy of choice was to step through each result, populated dynamically depending which taxonomy term has led them here, and fill a bucket with those results, then display each one appropriately.

In other words, I want the WordPress loop to tell me WHICH things to display, then my own iteration to decide HOW to display them. This seemed like a simple strategy, but loops like the following appear to be always displaying my entire bucket, although I am nowhere telling it to actually print that bucket. Narrowing it down to a minimal example I have the following, which still is printing out $bucket. What is going on?

$bucket = array();
while ( have_posts() ) {
    the_post();
    $bucket[]=the_meta(); // this is all printed to the screen. Why?
}

Advertisement

Answer

the_meta(); // this is all printed to the screen. Why?

WordPress has this concept of the_{name of function} and get_the_{name of function}. For example, the_title and get_the_title. the_title will echo out the title into the page but get_the_title will return the title instead.

the_{name of function} will echo out the result.
get_the_{name of function}, on the other hand, will return the result.

Read more on that

If you need to return the result instead of echoing it out into the page then use this version of the function: get_the_{name of function}.

So you could use the following code:

$bucket = array();

while ( have_posts() ) {
    the_post();
    $bucket[]=get_post_meta(get_the_ID());
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement