需要给'header_dark'
标签添加一个类<body>
,前提是内容中没有标签 <section>
,下面是我写的代码,但是不行。
function add_dark_class_to_head() {
if (is_singular()) {
$post_content = get_post_field('post_content', get_the_ID());
$main_section_pattern = '/<main\b[^>]*>(.*?)<section\b[^>]*>/s';
if (preg_match($main_section_pattern, $post_content)) {
add_filter('body_class', function ($classes) {
$classes[] = 'header_dark';
return $classes;
});
}
}
}
add_action('wp_head', 'add_dark_class_to_head');
告诉我可能是什么问题?我检查错了什么?*内容保存在标准表中WP
并通过指定Classic Editor
header.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover"><meta name="format-detection" content="telephone=no">
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div class="wrapper">
<header>
</header>
<main id="main" class="main">
页面.php
<?php get_header(); ?>
<div class="container">
<div id="content" class="col_content">
<div <?php post_class('post section py-md') ?> id="post-<?php the_ID(); ?>">
<div class="title">
<?php am_the_custom_title('h1'); ?>
</div>
<div class="entry">
<?php the_content(__('Read more', 'am')); ?>
<div class="clear clearfix"></div>
<?php wp_link_pages(array('before' => '<div class="page-link"><p><span>' . __('Pages:', 'am') . '</span>', 'after' => '</p></div>')); ?>
<?php edit_post_link(__('Edit', 'am'), '<br /><p>', '</p>'); ?>
</div>
</div>
</div>
</div>
<?php get_footer(); ?>
页脚.php
</main>
<footer class="page-footer"></footer>
</div>
<?php wp_footer(); ?>
</body>
</html>
这是代码:
一般来说,
#<main .*?</section#s
只要布局有效,即使是这个常规赛也应该适合您。如果布局可能无效,则需要更正布局。这是第一点,你的逻辑应该已经成立了。接下来你需要处理 WordPress。
get_post_field
接收帖子的内容并对其进行过滤以进行显示,默认情况display
下第三个参数位于此处。也就是说,在这种情况下你需要问自己四个问题:wp_head
?get_post_field
?收到它。你确定那里没有任何东西被屏蔽吗?body_class
我确定我能影响这个地方的钩子吗?至于逻辑本身,你确定在没有标签的情况下你总是有一个黑暗的主题吗
<section>
?您确定这种行为将来不会改变并且不会导致微妙的错误吗?您确定要将此标签埋入浅色主题中吗?))您准备好使用正则表达式绕过每篇文章的输出,而不仅仅是输出内容吗?也就是说,首先你需要回答这些问题,然后再解决问题。您可以采用另一种方式,通过命名帖子元字段
dark-theme
并将其设为单选按钮来创建帖子元字段。好吧,我也确信有 50 多个选项可以在不使用拐杖的情况下解决这个问题