简体   繁体   中英

Iterate through an array in wordpress php

I'm trying to iterate through this array with 'foreach' to get [post_title]. But unfortunately it's printing me nothing in my browser. Can anybody explain I can iterate through this array?

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
    )

)

Here's my foreach loop code:

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

            foreach ($post as $myposts ) {

                        echo $post['post_title'];
                 }             
}

Again, I need to get the value of post_title but I get no output. Help is appreciated.

You have an object inside an array. So you need to do something like

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

Or what have you tried so far?

Try this:

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

your code should be like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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