【问题标题】:Getting WP Functions to Return rather than Printing Immediately让 WP 函数返回而不是立即打印
【发布时间】:2009-10-14 14:13:22
【问题描述】:

我正在尝试在“循环”中构建一个数组,该数组由the_title()the_excerpt()the_permalink() 等各种函数提供的值组成。我想做一些类似于下面的事情。不幸的是,这些函数中的大多数会立即打印它们的结果而不是返回它们。此外,我已经检查了这些参数的可用参数,但没有找到任何强制返回的选项。

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()
    );
  }
}

【问题讨论】:

    标签: php wordpress function


    【解决方案1】:

    具有可猜测名称的替代函数

    显然有几种不同的方法可以解决这个问题。如前所述,某些函数将附带一个替代函数,该函数仅在开头添加“get_”。例如the_title() 打印标题,而get_the_title() 返回标题。

    名称不易猜到的替代函数

    其他函数不遵循这种做法。例如,the_permalink() 没有名为 get_the_permalink() 的替代项。相反,它的替代方案只是get_permalink()。这可能会造成混淆,因此我建议您在 Template Tags 页面上进行查找。

    偶尔的布尔参数(并非所有函数通用)

    此外,一些函数将包含一个允许您更改正常行为的参数。例如,如果您不想使用get_the_title(),您可以简单地使用以下内容:

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

    这会将布尔值设置为 false,这意味着该值将被返回而不是回显。

    【讨论】:

      【解决方案2】:

      我认为很多像 the_*() 这样的 Wordpress 函数都有像 get_the_*() 这样的替代方法。

      【讨论】:

      • 这对某些人来说是正确的,但对于像the_permalink()这样的其他人则不然
      • 我刚下载了WP 2.8.4,在link-template.php中有一个get_permalink()函数,the_permalink()使用了这个函数。
      • @VolkerK 谢谢。有什么比这更好的一致命名案例:)
      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      相关资源
      最近更新 更多