在 WordPress 开发中,当需要频繁展示复杂 HTML 内容(如数据表格、地图组件、自定义页面)时,传统方式往往导致代码冗余、维护困难。实际上只需要把html注册成短代码即可,通过标准化注册方法,实现本地 HTML 文件的一键调用,这样就能批量把html注册成短代码在wordpress中,非常简单。
<?php
//统一获取本地HTML输出(支持批量注册)
function create_html_shortcodes($shortcode_mappings) {
foreach ($shortcode_mappings as $shortcode_name => $relative_path) {
add_shortcode($shortcode_name, function() use ($relative_path) {
$subtheme_dir = get_stylesheet_directory();
$file_path = trailingslashit($subtheme_dir) . ltrim($relative_path, '/');
if (@is_readable($file_path)) {
$content = file_get_contents($file_path);
return ($content !== false) ? $content : error_html('数据获取失败');
}
return error_html('文件不可访问:' . esc_html($file_path));
});
}
}
// 统一错误处理(增强版)
function error_html($message) {
return '<div class="shortcode-error" style="color:red; border:1px dashed #ccc; padding:10px; margin:15px 0">'
. '⚠️ 内容加载失败: '. esc_html($message) .'</div>';
}
$all_shortcodes = [
// 地图类
'display_gaode_map' => 'html/map/gaode.html',
'display_baidu_map' => 'html/map/baidu.html',
// 表格类(只需在此扩展)
'display_ceshi_table' => 'html/table/re3200.html',
'display_ceshi123_table' => 'html/table/diaodu.html',
//页面类调用
'display_disclaimer_page' => 'html/page/disclaimer.html',
'display_realverse_page' => 'html/page/realverse-page.html',
];
// 批量注册所有短代码
create_html_shortcodes($all_shortcodes);
本文作者:ZKCOI
文章名称:WordPress 短代码批量本地html:实现 HTML 内容的高效调用与管理
文章链接:https://www.zkcoi.com/365up/program/4300.html
本站资源仅供个人学习和交流,如若转载,请注明出处,详见《免责声明》。
微信扫一扫
支付宝扫一扫 