问题描述
所以这可能看起来像是一件很美的事情,但是跟着我来。
我试图通过 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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。