首页 > 解决方案 > 在 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 的香草版本,我编写了所有功能。

有什么我想念的吗?

标签: phpwordpressfunctionsearchfilter

解决方案


您可以使用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对象。


推荐阅读