You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复WordPress文章中PPT附件嵌入显示的代码问题

修正WordPress文章中嵌入PPT的代码问题

原代码存在三个核心问题:

  • 仅获取附件数据但未输出渲染PPT的iframe结构
  • 查询的是全站所有PPT附件,而非当前文章关联的附件
  • MIME类型仅覆盖旧版.ppt格式,未包含新版.pptx格式

以下是修正后的完整代码,可直接替换post.php中的对应片段:

<?php
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => array(
        'application/vnd.ms-powerpoint', // 旧版PPT格式
        'application/vnd.openxmlformats-officedocument.presentationml.presentation' // 新版PPTX格式
    ),
    'posts_per_page' => -1,
    'post_parent' => get_the_ID(), // 仅获取当前文章关联的附件
    'orderby' => 'menu_order', // 按附件上传顺序排列
    'order' => 'ASC'
);

$attachments = new WP_Query($args);

if ($attachments->have_posts()) :
    while ($attachments->have_posts()) : $attachments->the_post();
        $attachment_url = wp_get_attachment_url(get_the_ID());
        // 输出Office Online嵌入iframe
?>
        <iframe src="https://view.officeapps.live.com/op/embed.aspx?src=<?php echo esc_url($attachment_url); ?>" 
                width="100%" 
                height="500px" 
                frameborder="0"
                title="<?php echo esc_attr(get_the_title()); ?>">
        </iframe>
<?php
    endwhile;
endif;

wp_reset_postdata();
?>

关键改动说明:

  • 添加post_parent参数绑定当前文章,确保只加载当前文章的附件
  • 补充PPTX的MIME类型,兼容新版PowerPoint文件
  • 在循环内输出iframe结构,将获取到的附件URL传入Office Online嵌入地址
  • 使用esc_url()和esc_attr()做安全转义,避免XSS风险
  • 增加排序参数,保持附件显示顺序与上传顺序一致

内容的提问来源于stack exchange,提问作者Harsha Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 06:42:24