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

使用WordPress Rest API生成PDF时出现内部服务器错误求助

解决WordPress REST API生成PDF时的500内部服务器错误

核心问题排查与修复

1. 修正命名空间(use)的位置

PHP的use声明不能放在函数内部,必须放在全局作用域(文件顶部、所有函数/类定义之前)。你的代码把use写在get_location函数里,会直接触发语法错误,导致500错误。

修正后的代码结构:

// 先引入Dompdf的自动加载文件,再声明命名空间
require get_stylesheet_directory() . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
use Dompdf\Options;

add_action(
    'rest_api_init',
    function () {
        register_rest_route(
            'api',
            '/get_location',
            array(
                'methods'  => WP_REST_Server::READABLE,
                'callback' => 'get_location',
            )
        );
    }
);

function get_location() {
    global $wpdb;
    $results = array();
    
    $options = new Options();
    $options->set( 'isRemoteEnabled', true );
    
    // 初始化Dompdf并生成PDF
    $dompdf = new Dompdf( $options );
    $dompdf->loadHtml( 'hello world<br/>TEST' );
    $dompdf->setPaper( 'A4', 'landscape' );
    $dompdf->render();
    
    $output = $dompdf->output();
    $now    = strtotime( 'now' );
    $save_path = get_stylesheet_directory() . '/dompdf/' . $now . '.pdf';
    
    // 尝试写入文件并返回状态
    if (file_put_contents( $save_path, $output )) {
        $results['status'] = 'success';
        $results['file_path'] = $save_path;
    } else {
        $results['status'] = 'error';
        $results['message'] = '无法写入PDF文件,请检查目录权限';
    }

    return $results;
}

2. 验证文件路径正确性

  • 确认dompdf文件夹确实在当前主题(子主题)的目录下,get_stylesheet_directory()指向子主题目录,若使用父主题请改用get_template_directory()。
  • 可通过在函数中添加var_dump(get_stylesheet_directory() . '/dompdf/autoload.inc.php');输出路径,验证文件是否存在。

3. 修复目录写入权限

  • 将dompdf目录的权限设置为755或775(根据服务器配置调整),确保PHP进程拥有写入权限。
  • 可在代码中提前检查目录可写性:
$pdf_dir = get_stylesheet_directory() . '/dompdf/';
if (!is_writable($pdf_dir)) {
    return array('error' => '目录不可写,请调整dompdf文件夹权限');
}

4. 开启调试模式定位具体错误

在wp-config.php中开启WordPress调试,查看具体错误日志:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

调试日志会保存在wp-content/debug.log中,里面会记录具体错误原因(如文件缺失、权限不足、语法错误等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:31:03