【问题标题】:Passing array data to a variable in a loop将数组数据传递给循环中的变量
【发布时间】:2019-01-14 15:59:39
【问题描述】:

如何在循环中将$the_slug 的内容传递给$post_name 变量?

$tags = get_the_tags();
foreach ($tags as $tag){

global $post;
$the_slug = $tag->slug; //contains 10ish words that associate with my permalinks: welcome, home, about, contact, etc

$post_id = 'welcome';
$post_name = $the_slug; //fails to populate here
$queried_post = get_post($post_name); //if changed to $post_id works but only 'welcome' post
$excerpt = $queried_post->post_excerpt;
$excerpt = apply_filters('the_content', $excerpt);
$excerpt = str_replace(']]>', ']]>', $excerpt);
echo $excerpt . "\n\n";
}

感谢您的关注。

【问题讨论】:

  • 我们需要更多信息。 $tag->slug 是数组还是字符串? get_post 函数长什么样子?
  • get_post 的第一个参数必须是 Post ID 或 post 对象。我想说,这很可能是 stackoverflow.com/questions/14979837/… 的副本
  • $tag->slug 包含字符串:welcome、home、about、contact 等...$get_posts = get_posts($tag->slug);...get_posts 是一个 wordpress 数组,包含元:[ID]、[post_content]、[post_title]、[post_excerpt]、[post_status]、[comment_status] 等...我试图让我的标签描述提取同名/slug 的帖子摘录.

标签: php arrays variables


【解决方案1】:

您可以使用 foreach 循环遍历数组:

foreach($the_slug as $slug){
   $post_name = $slug;
   $queried_post = get_post($post_name); $excerpt = $queried_post->post_excerpt;
   $excerpt = apply_filters('the_content', $excerpt);
   $excerpt = str_replace(']]>', ']]>', $excerpt);
   echo $excerpt . "\n\n";
}

【讨论】:

  • 谢谢,这更接近我想要实现的目标。我认为,我收到了一个“为 foreach() 提供的无效参数”,它指向我的数组。转储的数组包含 10 个应该可以工作的字符串,不是吗?
  • 你可以在这里发布结果:var_dump($the_slug) 吗?
  • $the_slug = $tag->slug; var_dump ($the_slug); string(7) "welcome" string(4) "home" string(5) "about" string(7) "contact"......我知道这是关于遍历数组的东西,但我很难看到什么。标签正在显示,我可以提取我所在的帖子的摘录,但不能提取链接到我的标签的帖子。我想我应该能够使用一个变量来添加到 foreach 循环中。
  • 它没有说 $the_slug 是一个数组,它应该像 array(3){[0]=> string(7) "welcome" [1]=>string(4) " home" [2]=>string(5) "about" [3]=>string(7) "contact"} 你粘贴了整个输出吗?
  • 现在说得通了。谢谢。认为我需要重新编写我的函数。我的印象是该变量是一个数组,因为它在 foreach 循环中的不同帖子中循环。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-28
  • 2016-10-02
  • 2018-01-20
  • 2019-06-28
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多