AJDEV AJDEV - 29 days ago 7
PHP Question

Get array value in $wp_query->posts var_dump

I have the following code:

$posts = $wp_query->posts;
foreach($posts as $post){
var_dump($post);
}


This will grab all the posts for the query that is being run and display all the posts information. The var_dump looks like this:

object(WP_Post)#84 (24) {
["ID"]=> int(1190)
["post_author"]=> string(1) "1"
["post_date"]=> string(19) "2016-10-20 14:17:55"
["post_date_gmt"]=> string(19) "2016-10-20 03:17:55"
["post_content"]=> string(0) ""
["post_title"]=> string(21) "Chilled water systems"
["post_excerpt"]=> string(0) ""
["post_status"]=> string(7) "publish"
["comment_status"]=> string(6) "closed"
["ping_status"]=> string(6) "closed"
["post_password"]=> string(0) ""
["post_name"]=> string(21) "chilled-water-systems"
["to_ping"]=> string(0) ""
["pinged"]=> string(0) ""
["post_modified"]=> string(19) "2016-10-21 11:23:49"
["post_modified_gmt"]=> string(19) "2016-10-21 00:23:49"
["post_content_filtered"]=> string(0) ""
["post_parent"]=> int(1182)
["guid"]=> string(48) "http://siteurl.com"
["menu_order"]=> int(0) **
["post_type"]=> string(4) "page"**
["post_mime_type"]=> string(0) ""
["comment_count"]=> string(1) "0"
["filter"]=> string(3) "raw"
}


I am wondering how can I get the post_type value from that var_dump. (text in bold) I have tried:

print_r($post['post_type']);
print_r($post[0]['post_type']);

Answer

Try this:

echo $post->post_type

More details:

If order the output, you can see:

object(WP_Post)#84 (24)
{
["ID"]=> int(1190) 
["post_author"]=> string(1) "1" 
["post_date"]=> string(19) "2016-10-20 14:17:55" 
["post_date_gmt"]=> string(19) "2016-10-20 03:17:55" 
["post_content"]=> string(0) "" 
["post_title"]=> string(21) "Chilled water systems" 
["post_excerpt"]=> string(0) "" 
["post_status"]=> string(7) "publish" 
["comment_status"]=> string(6) "closed" 
["ping_status"]=> string(6) "closed" 
["post_password"]=> string(0) "" 
["post_name"]=> string(21) "chilled-water-systems" 
["to_ping"]=> string(0) "" 
["pinged"]=> string(0) "" 
["post_modified"]=> string(19) "2016-10-21 11:23:49" 
["post_modified_gmt"]=> string(19) "2016-10-21 00:23:49" 
["post_content_filtered"]=> string(0) "" 
["post_parent"]=> int(1182) 
["guid"]=> string(48) "http://siteurl.com" 
["menu_order"]=> int(0) 
["post_type"]=> string(4) "page" 
["post_mime_type"]=> string(0) "" 
["comment_count"]=> string(1) "0" 
["filter"]=> string(3) "raw"
}

You have a object, and for access to object's fields, you must use ->, So, You can use $post->post_type for post type target.

Complete code:

$posts = $wp_query->posts;
foreach($posts as $post){
    var_dump($post->post_type);
}