language-utils.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Internals
  6. * @since 5.9.0
  7. */
  8. /**
  9. * Group of language utility methods for use by WPSEO.
  10. * All methods are static, this is just a sort of namespacing class wrapper.
  11. */
  12. class WPSEO_Language_Utils {
  13. /**
  14. * Returns the language part of a given locale, defaults to english when the $locale is empty.
  15. *
  16. * @param string $locale The locale to get the language of.
  17. *
  18. * @returns string The language part of the locale.
  19. */
  20. public static function get_language( $locale = null ) {
  21. $language = 'en';
  22. if ( empty( $locale ) || ! is_string( $locale ) ) {
  23. return $language;
  24. }
  25. $locale_parts = explode( '_', $locale );
  26. if ( ! empty( $locale_parts[0] ) && ( strlen( $locale_parts[0] ) === 2 || strlen( $locale_parts[0] ) === 3 ) ) {
  27. $language = $locale_parts[0];
  28. }
  29. return $language;
  30. }
  31. /**
  32. * Returns the user locale for the language to be used in the admin.
  33. *
  34. * WordPress 4.7 introduced the ability for users to specify an Admin language
  35. * different from the language used on the front end. This checks if the feature
  36. * is available and returns the user's language, with a fallback to the site's language.
  37. * Can be removed when support for WordPress 4.6 will be dropped, in favor
  38. * of WordPress get_user_locale() that already fallbacks to the site's locale.
  39. *
  40. * @returns string The locale.
  41. */
  42. public static function get_user_locale() {
  43. if ( function_exists( 'get_user_locale' ) ) {
  44. return get_user_locale();
  45. }
  46. return get_locale();
  47. }
  48. /**
  49. * Returns the full name for the sites' language.
  50. *
  51. * @return string The language name.
  52. */
  53. public static function get_site_language_name() {
  54. require_once ABSPATH . 'wp-admin/includes/translation-install.php';
  55. $translations = wp_get_available_translations();
  56. $locale = get_locale();
  57. $language = isset( $translations[ $locale ] ) ? $translations[ $locale ]['native_name'] : 'English (US)';
  58. return $language;
  59. }
  60. }