views:

87

answers:

2

I'm trying to build an array within "The Loop" of values provided from various functions like the_title(), the_excerpt(), the_permalink() and others. I'd like to do something similar to what follows. The unfortunate thing is that most of these functions immediately print their results rather than returning them. Furthermore, I have checked the available parameters for these, and haven't found any option to force a return.

if (have_posts()) {
  while (have_posts()) {
    the_post();
    $items[] = array(
      "id" => get_the_id(), "the_title" => the_title(), 
      "the_excerpt" => the_excerpt(), "the_permalink" => the_permalink()
    );
  }
}
+1  A: 

I think a lot of the Wordpress functions like the_*() have alternatives like get_the_*() which do exactly this.

Tom Haigh
That is true for some, but not for others like `the_permalink()`
Jonathan Sampson
I just downloaded WP 2.8.4 and there is a function get_permalink() in link-template.php and the_permalink() uses this funtion.
VolkerK
@VolkerK Thank you. What better case for consistent-naming than this :)
Jonathan Sampson
+4  A: 

Alternative Functions with Guessable Names

There are apparently a couple different ways to tackle this issue. As noted earlier, some functions will come with an alternative function that merely prepends "get_" to the beginning. For instance the_title() prints the title, whereas get_the_title() returns the title.

Alternative Functions with Less-Guessable Names

Other functions don't follow this practice. For instance, the_permalink() has no alternative called get_the_permalink(). Instead, its alternative is simply get_permalink(). This can be confusing, so I reccomend you perform look-ups on the Template Tags page.

The Occasional Boolean Parameter (Not Common to all functions)

Additionally, some functions will contain a parameter which allows you to alter the normal behavior. For instance, if you don't wish to use get_the_title(), you could simply use the following:

<?php $title = the_title('echo=0'); ?>

This sets the boolean value to false, meaning the value will be returned rather than echo'd.

Jonathan Sampson