首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为posts子集返回带有自定义div类的the_content()

为posts子集返回带有自定义div类的the_content()
EN

WordPress Development用户
提问于 2023-01-29 16:02:16
回答 1查看 110关注 0票数 4

是否可以让the_content()函数使用自定义的div类(即the-content以外的东西)返回D1中的post内容?

我有一个独特的帖子,我试图布局,要求样式的主要内容块,是不同的,几乎所有其他帖子在网站上。我只想为这个帖子子集创建一个自定义类。

EN

回答 1

WordPress Development用户

发布于 2023-01-29 20:46:32

这可以通过多种不同的方式来完成。例如:

1.使用the_content过滤器挂钩:

使用the_content过滤器钩子将the_content()函数调用的输出包装为所需的div

您可以在主题的functions.php文件或自定义插件中尝试以下代码:

代码语言:javascript
复制
add_filter( 'the_content', 'wpse_specific_the_content' );
function wpse_specific_the_content( $content ) {
    // logic to identify unique posts
    // for example, using specific post ID
    $unique_ids = array (12, 14, 21);
    // current post ID
    $id = get_the_id();
    if( in_array( $id, $unique_ids ) ) {
        return '' . $content . '';
    }
    return $content;
}

2.使用post_class过滤器钩子:

实际上,您不需要将the_content()包装在附加的div中。相反,您可以使用post_class过滤器挂钩。

这样,您就可以为需要它们的不同文章和页面分配唯一的CSS类,并根据这些CSS类对它们进行样式设计。

例如:

代码语言:javascript
复制
add_filter( 'post_class', 'wpse_filter_post_class' );
function wpse_filter_post_class( $class ) {
    $unique_ids = array (12, 14, 21);
    $id = get_the_id();
    if( in_array( $id, $unique_ids ) ) {
        // add these custom CSS classes to matching posts
        $add = array( 'custom-posts', 'some-class' );
        $class = array_merge( $add, $class );
    }
    return $class;
}

现在,按照您需要的方式瞄准这个类:

代码语言:javascript
复制
.custom-posts {
    background-color: gold;
}
.custom-posts .entry-content {
    background-color: red;
}

3.使用body_class过滤器钩子:

如果您需要对整个页面设计进行更通用的控制(与post_class将提供的内容相比),那么您可以使用body_class筛选器钩子修改类,相同的post_class过滤器钩子显示在上面。

如下所示:

代码语言:javascript
复制
add_filter( 'body_class', 'wpse_filter_body_class' );
function wpse_filter_body_class( $class ) {
    // this check is needed for body_class hook,
    // because the current page may not be a single post at all.
    if ( is_single() ) {
        $unique_ids = array (12, 14, 21);
        $id = get_the_id();
        if( in_array( $id, $unique_ids ) ) {
            $add = array( 'custom-body' );
            $class = array_merge( $add, $class );
        }   
    }
    return $class;
}

现在,您可以使用以下CSS来针对自定义post页面:

代码语言:javascript
复制
body.custom-body .any-inner-content-class {
    color: blue;
}

由于这个自定义类被添加到标记中,这样您就可以将页面中的任何元素作为目标。

票数 3
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/413298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档