WordPress 的架構種有幾種不同類型的頁面,因此想嘗試看看在不同類型的頁面呼叫 get_psot 和 get_queried_object 會得到什麼。
我們會使用這個範例程式做測試:
<?php
print_r(get_post());
?>
<br/>
<br/>
<br/>
<br/>
<?php
print_r(get_queried_object());
?>
front-page.php (首頁)
get_post :取得「最新的一篇文章」
get_queried_object:取得空值
WP_Post Object
(
[ID] => 8
[post_author] => 1
[post_date] => 2023-10-19 16:31:59
[post_date_gmt] => 2023-10-19 16:31:59
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => 8
[to_ping] =>
[pinged] =>
[post_modified] => 2023-10-19 16:32:10
[post_modified_gmt] => 2023-10-19 16:32:10
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://lab.local/?p=8
[menu_order] => 0
[post_type] => post
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
404.php (找不到頁面)
get_post :取得空值
get_queried_object:取得空值
sinlge-post.php (單頁)
get_post :取得當下的文章
get_queried_object:取得當下的文章
WP_Post Object
(
[ID] => 8
[post_author] => 1
[post_date] => 2023-10-19 16:31:59
[post_date_gmt] => 2023-10-19 16:31:59
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => 8
[to_ping] =>
[pinged] =>
[post_modified] => 2023-10-19 16:32:10
[post_modified_gmt] => 2023-10-19 16:32:10
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://multi-site.local/?p=8
[menu_order] => 0
[post_type] => post
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
archive.php (分類法 - 列表頁面)
get_post :取得「最新的一篇文章」(如果該分類法下沒有任何文章則會取得空值)
get_queried_object:取得當下分類法 WP_Term
WP_Term Object
(
[term_id] => 1
[name] => Uncategorized
[slug] => uncategorized
[term_group] => 0
[term_taxonomy_id] => 1
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 1
[filter] => raw
[cat_ID] => 1
[category_count] => 1
[category_description] =>
[cat_name] => Uncategorized
[category_nicename] => uncategorized
[category_parent] => 0
)