【问题标题】:Accessing Values in an Array / Object?访问数组/对象中的值?
【发布时间】:2015-03-31 17:33:43
【问题描述】:

尝试遍历一组类别并显示每个类别的最新帖子的标题。

  $feed_sources = array('goose-creek','sleepy-creek','fobr');
  foreach ($feed_sources as $feed) {
    $args = array('category_name' => $feed, 'posts_per_page' => 1);
    $show = get_posts($args); 
    print_r($show);

此代码返回

Array ( [0] => WP_Post Object ( [ID] => 79 [post_author] => 1 [post_date] => 2015-03-19 08:58:40 [post_date_gmt] => 2015-03-19 09:58:40 [post_content] => 

但我无法通过 $show[0]['post_title']、$show[0][post_title] 或 $show[0]->'post_title' 访问它

另外,有没有一种简单的方法可以让这个数组与基本的主题函数一起工作,比如 the_title();内容();等等?

【问题讨论】:

  • 使用$show[0]->post_title
  • WP 函数通常使用全局 $post 变量。您可以设置它的值以使其工作。
  • 不返回任何东西 :(
  • 这种情况下如何设置全局$post变量?

标签: php wordpress wordpress-theming


【解决方案1】:

你应该把它改写成这样的:

$feed_sources = array('goose-creek','sleepy-creek','fobr');

foreach ($feed_sources as $feed) {
    $args = array('category_name' => $feed, 'posts_per_page' => 1);

    // we are creating new WP_Query object instead using get_posts() function 
    $shows = new WP_Query($args);

    $shows->the_post();
    // now you can use the_title() and the_content()
    the_title();
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 2020-09-19
    • 1970-01-01
    相关资源
    最近更新 更多