2016-11-10 37 views
0

我有以下代碼:

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

這將抓住所有的查詢正在運行的職位,並顯示所有的職位信息。後續代碼var_dump看起來是這樣的:

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" 
} 

我想知道我怎樣才能從該的var_dump值post_type。 (粗體文字)我曾嘗試:

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

回答

2

試試這個:

echo $post->post_type 

更多細節:

如果爲了輸出,你可以看到:

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" 
} 

你有一個對象,並且對於訪問對象的字段,您必須使用->,因此,您可以使用$post->post_type作爲帖子類型的目標。

完整代碼:

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

就像一個魅力 – AJDEV

+0

一兩件事。變量$ posts將在數組中有多個對象。我怎麼會得到一個,例如,如果它是一個正常的數組,你會使用'$ posts [0]' – AJDEV

+0

@AJDEV你可以使用這個:$ posts [0] - > post_type –