問題描述
所以這可能看起來像是一件很美的事情,但是跟著我來。
我試圖透過 pre_get_posts
操作新增一些邏輯。這是給我的整個 WP_Query 物件。 (見結尾)
我考慮過的事情是:
-
is_single()
– 太寬 -
is_singular()
– 使用起來太早,因為get_queried_object()
尚未設定。 -
$query->single
屬性 – 太寬了。 -
$query->get('post_type')
– 未設定,因為它使用name
屬性。
name
真的是唯一的指標嗎?
WP_Query Object
(
[query] => Array
(
[page] =>
[name] => abcs-of-mental-health
)
[query_vars] => Array
(
[page] =>
[name] => abcs-of-mental-health
[error] =>
[m] => 0
[p] => 0
[post_parent] =>
[subpost] =>
[subpost_id] =>
[attachment] =>
[attachment_id] => 0
[static] =>
[pagename] =>
[page_id] => 0
[second] =>
[minute] =>
[hour] =>
[day] => 0
[monthnum] => 0
[year] => 0
[w] => 0
[category_name] =>
[tag] =>
[cat] =>
[tag_id] =>
[author_name] =>
[feed] =>
[tb] =>
[paged] => 0
[comments_popup] =>
[meta_key] =>
[meta_value] =>
[preview] =>
[s] =>
[sentence] =>
[fields] =>
[menu_order] =>
[category__in] => Array
(
)
[category__not_in] => Array
(
)
[category__and] => Array
(
)
[post__in] => Array
(
)
[post__not_in] => Array
(
)
[tag__in] => Array
(
)
[tag__not_in] => Array
(
)
[tag__and] => Array
(
)
[tag_slug__in] => Array
(
)
[tag_slug__and] => Array
(
)
[post_parent__in] => Array
(
)
[post_parent__not_in] => Array
(
)
)
[tax_query] =>
[meta_query] =>
[queried_object] =>
[queried_object_id] => 0
[post_count] => 0
[current_post] => -1
[in_the_loop] =>
[comment_count] => 0
[current_comment] => -1
[found_posts] => 0
[max_num_pages] => 0
[max_num_comment_pages] => 0
[is_single] => 1
[is_preview] =>
[is_page] =>
[is_archive] =>
[is_date] =>
[is_year] =>
[is_month] =>
[is_day] =>
[is_time] =>
[is_author] =>
[is_category] =>
[is_tag] =>
[is_tax] =>
[is_search] =>
[is_feed] =>
[is_comment_feed] =>
[is_trackback] =>
[is_home] =>
[is_404] =>
[is_comments_popup] =>
[is_paged] =>
[is_admin] =>
[is_attachment] =>
[is_singular] => 1
[is_robots] =>
[is_posts_page] =>
[is_post_type_archive] =>
[query_vars_hash] => f473ebf7f725c2627dc5fd9a1429f626
[query_vars_changed] =>
[thumbnails_cached] =>
)
最佳解決方案
為了我自己的目的,我已經嘗試將之排除。據我所知
-
post_type
沒有真正設定為post
帖子型別的任何地方。 -
對於
page
帖子型別,我只看到queried_object
中的帖子型別鍵。 -
對於 CPT 型別,
query_vars
中還有一個post_type
金鑰,還有query
。 -
在這方面,導航選單看起來像其他 CPT 一樣。
資料非常不一致,但是如果您刪除頁面和 CPT,我相信您可以假設 post
型別。
編輯:@EricHolmes 的工作程式碼:
add_action( 'pre_get_posts', 'something_for_single_posts_only' ) ;
function something_for_single_posts_only( $query ) {
if( $query->is_main_query()
&& $query->is_singular()
&& ! $query->get( 'post_type' )
&& ! $query->is_page()
&& ! $query->is_attachment()
) {
// do something for single posts only.
}
}
我們檢查 is_singular,沒有帖子型別 (CPT 在 query_vars
中有 post_type
),而不是頁面或附件。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。