Created
June 16, 2017 14:07
-
-
Save Screenfeed/b0af3d3da21cbb276075605a86560b0e to your computer and use it in GitHub Desktop.
Use translations from #WordPress plugins first
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: GlotPress Last | |
* Plugin URI: https://www.screenfeed.fr | |
* Description: Prevent WP from loading a plugin's .mo files from the languages directory first. Instead, WP will first try to load the files from the plugin. | |
* Version: 1.0 | |
* Author: Grégory Viguier | |
* Author URI: https://www.screenfeed.fr/greg/ | |
* License: GPLv3 | |
* License URI: https://www.screenfeed.fr/gpl-v3.txt | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) { | |
die( 'Cheatin\' uh?' ); | |
} | |
global $wp_version; | |
if ( version_compare( $wp_version, '4.6' ) < 0 ) { | |
return; | |
} | |
add_filter( 'load_textdomain_mofile', 'sf_plugin_translations_first', 10, 2 ); | |
/** | |
* If we try to load a .mo file from wp-content/languages/plugins, return the path of the file from the related plugin instead (if the file exists). | |
* | |
* @since 1.0 | |
* @author Grégory Viguier | |
* | |
* @param string $mofile Path to the MO file. | |
* @param string $domain Text domain. Unique identifier for retrieving translated strings. | |
* @return string Path to a MO file. | |
*/ | |
function sf_plugin_translations_first( $mofile, $domain ) { | |
$langs_dir = WP_LANG_DIR . '/plugins/'; | |
if ( strpos( $mofile, $langs_dir ) !== 0 ) { | |
// It's not a file from wp-content/languages/plugins. | |
return $mofile; | |
} | |
// We need to grab the path of the folder within the plugin. It's dirty, but it's the only way. | |
$backtrace = debug_backtrace(); | |
if ( ! $backtrace ) { | |
return $mofile; | |
} | |
// The file name with a heading slash. | |
$file_name = str_replace( $langs_dir, '/', $mofile ); | |
foreach ( $backtrace as $trace ) { | |
// We need the 3rd argument passed to load_plugin_textdomain(). | |
if ( 'load_plugin_textdomain' !== $trace['function'] ) { | |
continue; | |
} | |
// Build the new file path. | |
$plugin_rel_path = isset( $trace['args'][2] ) ? $trace['args'][2] : false; | |
if ( false !== $plugin_rel_path ) { | |
$path = WP_PLUGIN_DIR . '/' . trim( $plugin_rel_path, '/' ); | |
} else { | |
$path = WP_PLUGIN_DIR; | |
} | |
if ( is_readable( $path . $file_name ) ) { | |
// We have an existing file \o/ | |
return $path . $file_name; | |
} | |
break; | |
} | |
return $mofile; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment