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

将主题翻译文件复制到Rate my post插件的代码实现求助

解决从主题复制翻译文件到Rate My Post插件的问题

错误原因说明

  • 错误1:copy()函数要求第二个参数必须是包含文件名的完整目标路径,仅传入目录路径会触发该错误。
  • 错误2:你的目标路径指向了主题子目录,而非Rate My Post插件的语言目录,正确路径应指向wp-content/plugins/rate-my-post/languages/。

修正后的实现代码

function copy_translation_files_to_rmp() {
    // 主题中翻译文件的源路径
    $source_po = get_stylesheet_directory() . '/languages/rate-my-post-fa_IR.po';
    $source_mo = get_stylesheet_directory() . '/languages/rate-my-post-fa_IR.mo';

    // Rate My Post插件的语言目标目录(确认插件目录名为rate-my-post,若不同请修改)
    $target_dir = WP_PLUGIN_DIR . '/rate-my-post/languages/';
    
    // 确保目标目录存在,不存在则递归创建
    if ( !is_dir($target_dir) ) {
        mkdir($target_dir, 0755, true);
    }

    // 拼接目标文件的完整路径
    $target_po = $target_dir . 'rate-my-post-fa_IR.po';
    $target_mo = $target_dir . 'rate-my-post-fa_IR.mo';

    // 复制PO文件
    if ( file_exists($source_po) ) {
        copy($source_po, $target_po) ?: error_log("复制PO文件失败:$source_po → $target_po");
    } else {
        error_log("源PO文件不存在:$source_po");
    }

    // 复制MO文件
    if ( file_exists($source_mo) ) {
        copy($source_mo, $target_mo) ?: error_log("复制MO文件失败:$source_mo → $target_mo");
    } else {
        error_log("源MO文件不存在:$source_mo");
    }
}

// 绑定到admin_init钩子,仅在后台执行,避免前端重复触发
add_action( 'admin_init', 'copy_translation_files_to_rmp' );

关键优化点

  • 使用get_stylesheet_directory()确保正确获取当前主题的绝对路径
  • 用WP_PLUGIN_DIR拼接插件语言目录,避免路径硬编码错误
  • 提前检查并创建目标目录,防止因目录缺失导致复制失败
  • 先验证源文件存在性,减少无意义的错误触发
  • 用error_log()记录错误,不干扰前端页面输出
  • 选择admin_init钩子,仅在后台初始化时执行,降低性能消耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:56:22