class-admin-asset-yoast-components-l10n.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin
  6. */
  7. /**
  8. * Localizes JavaScript files.
  9. */
  10. final class WPSEO_Admin_Asset_Yoast_Components_L10n {
  11. /**
  12. * Localizes the given script with the JavaScript translations.
  13. *
  14. * @param string $script_handle The script handle to localize for.
  15. *
  16. * @return void
  17. */
  18. public function localize_script( $script_handle ) {
  19. $translations = [
  20. 'yoast-components' => $this->get_translations( 'yoast-components' ),
  21. 'wordpress-seo' => $this->get_translations( 'wordpress-seojs' ),
  22. ];
  23. wp_localize_script( $script_handle, 'wpseoYoastJSL10n', $translations );
  24. }
  25. /**
  26. * Returns translations necessary for JS files.
  27. *
  28. * @param string $component The component to retrieve the translations for.
  29. * @return object The translations in a Jed format for JS files.
  30. */
  31. protected function get_translations( $component ) {
  32. $locale = WPSEO_Language_Utils::get_user_locale();
  33. $file = plugin_dir_path( WPSEO_FILE ) . 'languages/' . $component . '-' . $locale . '.json';
  34. if ( file_exists( $file ) ) {
  35. $file = file_get_contents( $file );
  36. if ( is_string( $file ) && $file !== '' ) {
  37. return json_decode( $file, true );
  38. }
  39. }
  40. return null;
  41. }
  42. }