是否可以让the_content()函数使用自定义的div类(即the-content以外的东西)返回D1中的post内容?
我有一个独特的帖子,我试图布局,要求样式的主要内容块,是不同的,几乎所有其他帖子在网站上。我只想为这个帖子子集创建一个自定义类。
发布于 2023-01-29 20:46:32
这可以通过多种不同的方式来完成。例如:
the_content过滤器挂钩:使用the_content过滤器钩子将the_content()函数调用的输出包装为所需的div。
您可以在主题的functions.php文件或自定义插件中尝试以下代码:
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;
}post_class过滤器钩子:实际上,您不需要将the_content()包装在附加的div中。相反,您可以使用post_class过滤器挂钩。
这样,您就可以为需要它们的不同文章和页面分配唯一的CSS类,并根据这些CSS类对它们进行样式设计。
例如:
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;
}现在,按照您需要的方式瞄准这个类:
.custom-posts {
background-color: gold;
}
.custom-posts .entry-content {
background-color: red;
}body_class过滤器钩子:如果您需要对整个页面设计进行更通用的控制(与post_class将提供的内容相比),那么您可以使用body_class筛选器钩子修改类,相同的post_class过滤器钩子显示在上面。
如下所示:
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页面:
body.custom-body .any-inner-content-class {
color: blue;
}由于这个自定义类被添加到标记中,这样您就可以将页面中的任何元素作为目标。
https://wordpress.stackexchange.com/questions/413298
复制相似问题