Bold Timeline 插件的底层架构与渲染链路
Bold Timeline 插件的底层架构与渲染链路
Bold Timeline 这类时间轴插件核心在于“数据结构 + 渲染层解耦”。从常见实现看,它通常会注册一个自定义文章类型(CPT)或自定义表来存储事件节点,再通过 shortcode / block 输出前端时间轴。底层流程一般是:后台保存事件(标题、时间、内容、媒体、排序权重)→ 前端查询并按时间或权重排序 → 组装成统一的 timeline item 数据 → 渲染模板(PHP/JS)输出。
为了减少主题耦合,插件会在 wp_enqueue_scripts 中按需加载 CSS/JS,并用 wp_localize_script 把时间轴配置(方向、动画、懒加载、分页)下发给前端脚本。若支持 Elementor/Gutenberg,则会额外挂接控件/Block 的 controls,最终仍回落到同一套渲染函数,保证不同编辑器一致性。
标题2:关键代码实现:CPT + Shortcode + 资源按需加载
下面是一个典型的“时间轴事件 CPT + shortcode 输出”的底层骨架(与 Bold Timeline 的思路一致):
// 1) 注册 Timeline 事件 CPT
add_action('init', function () {
register_post_type('bold_timeline', [
'label' => 'Timeline Events',
'public' => false,
'show_ui' => true,
'supports' => ['title','editor','thumbnail','custom-fields'],
]);
});
// 2) Shortcode:查询并输出时间轴
add_shortcode('bold_timeline', function($atts){
$q = new WP_Query([
'post_type' => 'bold_timeline',
'posts_per_page' => -1,
'meta_key' => 'event_date',
'orderby' => 'meta_value',
'order' => 'ASC'
]);
ob_start();
echo '<div class="bold-timeline" data-anim="fade">';
while($q->have_posts()){ $q->the_post();
$date = get_post_meta(get_the_ID(),'event_date',true);
echo '<article class="tl-item">';
echo '<time class="tl-date">'.esc_html($date).'</time>';
echo '<h3 class="tl-title">'.get_the_title().'</h3>';
echo '<div class="tl-content">'.apply_filters('the_content', get_the_content()).'</div>';
echo '</article>';
}
wp_reset_postdata();
echo '</div>';
return ob_get_clean();
});
// 3) 按需加载资源
add_action('wp_enqueue_scripts', function(){
if (is_singular() && has_shortcode(get_post()->post_content, 'bold_timeline')) {
wp_enqueue_style('bold-timeline', plugins_url('assets/timeline.css', __FILE__));
wp_enqueue_script('bold-timeline', plugins_url('assets/timeline.js', __FILE__), ['jquery'], null, true);
}
});
前端 timeline.js 一般只做三件事:读取容器 data 配置、计算节点位置(纵向/横向)、用 IntersectionObserver 触发动画/懒加载。Bold Timeline 的价值点就在于把这些能力封装成可复用渲染核心,让你在不改主题的情况下快速挂载“事件流 UI”,同时保证性能与可维护性。
评论 0