繁体   English   中英

在Wordpress PHP中遍历数组

[英]Iterate through an array in wordpress php

我试图用'foreach'遍历此数组以获得[post_title]。 但不幸的是,它没有在浏览器中打印任何内容。 谁能解释我可以遍历这个数组?

Array
(
[0] => WP_Post Object
    (
        [ID] => 6
        [post_author] => 1
        [post_date] => 2017-11-09 12:56:27
        [post_date_gmt] => 2017-11-09 12:56:27
        [post_content] => 
        [post_title] => Hi everybody
        [post_excerpt] => 
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] => 
        [post_name] => hi-everybody
        [to_ping] => 
        [pinged] => 
        [post_modified] => 2017-11-09 12:56:27
        [post_modified_gmt] => 2017-11-09 12:56:27
        [post_content_filtered] => 
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )

[1] => WP_Post Object
    (
        [ID] => 1
        [post_author] => 1
        [post_date] => 2017-11-06 22:35:17
        [post_date_gmt] => 2017-11-06 22:35:17
        [post_content] => Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
        [post_title] => Hello world!
        [post_excerpt] => 
        [post_status] => publish
        [comment_status] => open
        [ping_status] => open
        [post_password] => 
        [post_name] => hello-world
        [to_ping] => 
        [pinged] => 
        [post_modified] => 2017-11-06 22:35:17
        [post_modified_gmt] => 2017-11-06 22:35:17
        [post_content_filtered] => 
        [post_parent] => 0
        [menu_order] => 0
        [post_type] => post
        [post_mime_type] => 
        [comment_count] => 1
        [filter] => raw
    )

)

这是我的foreach循环代码:

    $my_posts = new WP_Query;
    $myposts = $my_posts->query( array('post_type' => 'post'));

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }             
}

同样,我需要获取post_title的值,但是没有输出。 感谢帮助。

您在数组中有一个对象。 所以你需要做类似的事情

foreach ($array[WP_Post] as $item) {
  echo $item;
}

或者到目前为止您尝试了什么?

尝试这个:

$my_posts = new WP_Query; 
$myposts = $my_posts->query( array('post_type' => 'post')); 
foreach ($post as $myposts ) { 
    echo $myposts->post_title; 
} 

您的代码应如下所示:

$my_posts = new WP_Query;
$myposts = $my_posts->query( array('post_type' => 'post'));

foreach ($myposts  as $post )
{
    echo $post->post_title;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM