基于帖子类别的自定义正文标记

时间:2014-02-14 14:05:10

标签: php wordpress

我需要根据帖子类型和类别添加一个body类。

我试过这个,但它似乎不起作用。

add_filter( 'body_class', 'custom_body_class' );

function custom_body_class( $classes ) {
    global $post;

    if ( 'service_provider' == $post->post_type AND 'educational_services' == $post->post_category ) {
        $classes[] = 'body-purple';
        return $classes;
    }
}

这会返回此错误 -

警告:join()[function.join]:在第394行的/home/davedevj/public_html/wp-includes/post-template.php中传递的参数无效class =“”>

所以我在其中添加了一些额外的代码:

add_filter( 'body_class', 'custom_body_class' );

function custom_body_class( $classes ) {
    global $post;

    if ( 'service_provider' == $post->post_type AND 'educational_services' == $post->post_category ) {
        $classes[] = 'body-purple';
        return $classes;
    }
    else {
         $classes[] = '';
        return $classes;
    }
}

如果可能的话,我需要没有else语句。

但主要问题是即使这样也行不通。我试过离开post_category部分而没有AND,只是if条件 - 但没有运气。

1 个答案:

答案 0 :(得分:0)

您的代码失败,因为没有post_category属性。这是我的版本:

function wpse_custom_body_class( $classes ) {
     // Check user is on a single service_provider post.
     if ( ! is_singular( 'service_provider' ) )
         return $classes;     

     // Get categories assigned to post.
     $categories = get_the_category();

     // Check categories were found.
     if ( ! $categories )
         return $classes;

     foreach ( $categories as $category ) {
         if ( 'educational_services' == $category->name ) {
             $classes[] = 'body-purple'; 
         }
     }

     return $classes;
}
add_filter( 'body_class', 'wpse_custom_body_class' );