php - 在 WordPress 中尝试添加过滤器以在正文中添加类时搜索功能和全局 $post 对象之间的冲突
问题描述
这是我的问题。
body
如果帖子/页面是另一个帖子的子级,我想向帖子或页面的标签添加一个类。
到目前为止,一切都很好:
function add_class_to_custom_post_parent($classes) {
global $post;
if ($post->post_parent > 0) {
$classes[] = 'children-custom-post-page';
}
return $classes;
}
add_filter( 'body_class', 'add_class_to_custom_post_parent' );
它就像一个魅力,但是当我在 WordPress 中使用搜索功能时(当我尝试根据一个单词返回所有帖子或页面时),系统仍然可以工作,但它会抛出这个错误:
注意:尝试在第 301 行的 functions.php 中获取非对象的属性
为了调试它,我尝试了不同的解决方案:
我将代码包装在条件中if (is_page()) {}
,但随后代码无法在后期工作(而且我认为这不是正确的解决方案)并且我尝试var_dump()
使用全局$post
对象,但由于某种原因在该页面中它不会返回任何内容.
所以现在我试图怀疑有什么问题。
问题是我使用了一个简单的主题,所以没有添加或额外的插件,它是 WordPress 的香草版本,我编写了所有功能。
有什么我想念的吗?
解决方案
您可以使用is_singular()函数将 CSS 类添加到body
标签中,仅用于帖子和页面(如果您指定它们,甚至还可以自定义帖子类型):
function add_class_to_custom_post_parent($classes) {
if ( is_singular(array('post', 'page')) ) {
global $post;
if ($post->post_parent > 0) {
$classes[] = 'children-custom-post-page';
}
}
return $classes;
}
add_filter( 'body_class', 'add_class_to_custom_post_parent' );
哦,您收到 PHP 通知的原因$post
是在您进行搜索时未设置:您没有看到帖子或页面,您看到的搜索结果模板没有为自己设置一个$post
对象。
推荐阅读
- android - 房间数据库android的问题
- python - NLP 神经网络的递归深度超出/内核死亡连接张量
- python - 有没有办法为 python plotly 热图创建分层轴标签?
- plantuml - PUML 序列图中激活矩形中的文本
- git - 是否有引用分支历史中提交之后的提交的语法?
- laravel - 启用字体子集时,laravel-dompdf 出现错误“未定义索引:glyf”
- python - CURLE_PEER_FAILED_VERIFICATION (60)
- java - orbot 作为代理与 jaunt web-scraping
- laravel - 如何从控制器异步调用 Laravel 自定义命令?
- c# - 如何在asp中使用flexbox将项目限制为每行两个项目?