如何通过钩子/短代码在Elementor弹窗中展示当前CPT内容?
在Elementor侧边弹窗中展示当前CPT文章内容的解决方案
方案1:自定义短代码(最简单直接)
直接编写短代码拉取当前项目的内容,随后在弹窗中插入该短代码即可:
// 将这段代码添加到主题的functions.php文件,或自定义插件中 function current_post_content_shortcode() { global $post; // 替换为你的自定义文章类型slug,例如'project' if ( is_singular('project') && $post ) { // 自动应用WordPress与Elementor的内容格式规则 return apply_filters('the_content', $post->post_content); } return ''; } add_shortcode('current_post_content', 'current_post_content_shortcode');
使用步骤:
- 把代码中的
'project'替换为你的CPT实际slug - 编辑Elementor弹窗,添加「短代码」部件,输入
[current_post_content]即可加载当前项目内容
方案2:用钩子动态注入内容
若不想使用短代码,也可通过钩子直接将内容插入弹窗:
// 添加到functions.php文件或自定义插件 function add_post_content_to_offcanvas() { global $post; // 替换CPT slug和弹窗内容区域的CSS选择器 if ( is_singular('project') && $post ) { ?> <script> document.addEventListener('DOMContentLoaded', () => { // 替换为你弹窗内容区域的实际CSS选择器,例如.elementor-popup-123 .elementor-popup-content const popupContainer = document.querySelector('.elementor-popup-content'); if (popupContainer) { popupContainer.insertAdjacentHTML('beforeend', '<?php echo esc_js(apply_filters("the_content", $post->post_content)); ?>'); } }); </script> <?php } } add_action('wp_footer', 'add_post_content_to_offcanvas');
注意事项:
- 需替换代码中的CPT slug和弹窗选择器,确保能精准定位到弹窗的内容承载区域
- 该方式无需在弹窗内添加额外部件,页面加载完成后内容会自动填充
额外提示
- 若使用Elementor Pro弹窗功能,需将弹窗设置为全局弹窗,并配置触发条件(如对应CPT页面的按钮点击、页面加载)
- 可为弹窗内的文章内容添加自定义CSS类,避免与弹窗原有样式冲突
- 测试前请清除缓存,确保代码生效
内容的提问来源于stack exchange,提问作者newbiedev
相关产品推荐
相关产品推荐

