WordPress特定分类文章特色图片下插入表格的实现方法
WordPress特定分类文章自动插入表格的实现方案
步骤1:创建独立表格文件
在你的WordPress主题目录(如wp-content/themes/你的主题名/)下新建stats-chaselogs.php文件,写入以下内容:
<?php // stats-chaselogs.php ?> <table width="100%" border="3"> <tbody> <tr> <td>GENERAL</td> <td>MARGINAL</td> <td>SLIGHT</td> </tr> <tr> <td>ENHANCED</td> <td>MODERATE</td> <td>HIGH</td> </tr> </tbody> </table>
步骤2:添加自动插入功能代码
在主题的functions.php文件末尾添加以下代码,替换$target_parent_category_id为你指定的父分类ID:
// 自动在指定父分类文章的特色图片后插入表格 add_filter('the_content', 'insert_table_after_featured_image'); function insert_table_after_featured_image($content) { // 仅处理单篇文章页面 if (!is_single()) { return $content; } // 替换为你的目标父分类ID $target_parent_category_id = 5; $post_id = get_the_ID(); $has_target_category = false; // 检查文章所属分类是否属于指定父分类 $categories = get_the_category($post_id); foreach ($categories as $category) { if ($category->parent == $target_parent_category_id || $category->term_id == $target_parent_category_id) { $has_target_category = true; break; } } if (!$has_target_category) { return $content; } // 引入表格文件内容 ob_start(); get_template_part('stats-chaselogs'); $table_html = ob_get_clean(); // 找到特色图片并插入表格 $featured_image_tag = get_the_post_thumbnail($post_id); if (!empty($featured_image_tag)) { $content = str_replace($featured_image_tag, $featured_image_tag . $table_html, $content); } else { // 无特色图片时直接插入正文开头 $content = $table_html . $content; } return $content; }
补充说明
- 你可以在WordPress后台分类编辑页面的URL中获取目标父分类的ID,替换代码中的
$target_parent_category_id值。 - 如果主题的特色图片是通过模板直接输出(未包含在
the_content中),可修改主题single.php文件,在特色图片输出代码后添加分类判断与表格引入:
// 在single.php的特色图片输出代码后添加 $target_parent_category_id = 5; if (has_category($target_parent_category_id) || in_category($target_parent_category_id)) { get_template_part('stats-chaselogs'); }
内容的提问来源于stack exchange,提问作者Tony Laubach
相关产品推荐
相关产品推荐

