开发者

Getting WP Functions to Return rather than Printing Immediately

开发者 https://www.devze.com 2022-12-08 18:04 出处:网络
I\'m trying to build an array within \"The Loop\" of values provided fr开发者_JAVA百科om various functions like the_title(), the_excerpt(), the_permalink() and others. I\'d like to do something simila

I'm trying to build an array within "The Loop" of values provided fr开发者_JAVA百科om 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()
    );
  }
}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号