如何添加基于自定义分类术语的Body类

时间:2012-07-31 作者:Josh2012

我正试图在某些WordPress页面的开头body标记中插入自定义分类法的slug作为类。到目前为止,我所做的是造成错误。

我在示例中找到了一些帮助herehere, 它可以工作,只是在没有“section”分类法中的术语的任何页面上都会出现错误。

错误是:

Warning: join() [function.join]: Invalid arguments passed in /home/*****/public_html/example.com/wp-includes/post-template.php on line 387
代码是:

// add classes to body based on custom taxonomy (\'sections\')
// examples: section-about-us, section-start, section-nyc
function section_id_class($classes) {
    global $post;
    $section_terms = get_the_terms($post->ID, \'section\');
    if ($section_terms && !is_wp_error($section_terms)) {
        $section_name = array();
        foreach ($section_terms as $term) {
            $classes[] = \'section-\' . $term->slug;
        }
    return $classes;
    }
}
add_filter(\'body_class\', \'section_id_class\');

2 个回复
最合适的回答,由SO网友:bueltge 整理而成

你的工作是什么$section_name? 你还必须得到回报;您可以使用if语句终止默认返回。如果if语句失败,这一点很重要。

也许这是可行的,但没有经过测试,可以从头开始写。

add_filter( \'body_class\', \'section_id_class\' );
// add classes to body based on custom taxonomy (\'sections\')
// examples: section-about-us, section-start, section-nyc
function section_id_class( $classes ) {
    global $post;

    $section_terms = get_the_terms( $post->ID, \'section\' );
    if ( $section_terms && ! is_wp_error( $section_terms ) ) {
        foreach ($section_terms as $term) {
            $classes[] = \'section-\' . $term->slug;
        }
    }

    return $classes;
}

SO网友:woony

对于与该节无关的页面,您通常会遇到错误。如果“if语句”失败,请确保还返回“$类”。

换句话说,请确保在此处添加一个else。

// add classes to body based on custom taxonomy (\'sections\')
// examples: section-about-us, section-start, section-nyc
function section_id_class($classes) {
global $post;
$section_terms = get_the_terms($post->ID, \'section\');
if ($section_terms && !is_wp_error($section_terms)) {
    $section_name = array();
    foreach ($section_terms as $term) {
        $classes[] = \'section-\' . $term->slug;
    }
else 
{  $classes = \'default-class\'; }
return $classes;
}
}
add_filter(\'body_class\', \'section_id_class\');
像这样的

结束