class.jetpack-pwa-manifest.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. class Jetpack_PWA_Manifest {
  3. /**
  4. * @var Jetpack_PWA_Manifest
  5. */
  6. private static $__instance = null;
  7. /**
  8. * When this query var is present, display the PWA manifest.
  9. *
  10. * @var string
  11. */
  12. const PWA_MANIFEST_QUERY_VAR = 'jetpack_app_manifest';
  13. /**
  14. * Singleton implementation
  15. *
  16. * @return Jetpack_PWA_Manifest
  17. */
  18. public static function instance() {
  19. if ( is_null( self::$__instance ) ) {
  20. self::$__instance = new Jetpack_PWA_Manifest;
  21. }
  22. return self::$__instance;
  23. }
  24. /**
  25. * Registers actions the first time that instance() is called.
  26. */
  27. private function __construct() {
  28. add_action( 'wp_head', array( $this, 'render_manifest_link' ) );
  29. add_action( 'amp_post_template_head', array( $this, 'render_manifest_link' ) );
  30. add_action( 'template_redirect', array( $this, 'render_manifest_json' ), 2 );
  31. }
  32. function render_manifest_link() {
  33. ?>
  34. <link rel="manifest" href="<?php echo esc_url_raw( $this->get_manifest_url() ); ?>">
  35. <meta name="theme-color" content="<?php echo esc_attr( Jetpack_PWA_Helpers::get_theme_color() ); ?>">
  36. <?php
  37. }
  38. public function get_manifest_url() {
  39. return add_query_arg(
  40. self::PWA_MANIFEST_QUERY_VAR, '1', home_url()
  41. );
  42. }
  43. function render_manifest_json() {
  44. // Do not load manifest in multiple locations
  45. if ( is_front_page() && isset( $_GET[ self::PWA_MANIFEST_QUERY_VAR ] ) && $_GET[ self::PWA_MANIFEST_QUERY_VAR ] ) {
  46. @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
  47. $theme_color = Jetpack_PWA_Helpers::get_theme_color();
  48. $manifest = array(
  49. 'name' => get_bloginfo( 'name' ),
  50. 'start_url' => get_home_url(),
  51. 'short_name' => substr( get_bloginfo( 'name' ), 0, 12 ),
  52. 'display' => 'standalone',
  53. 'background_color' => $theme_color,
  54. 'theme_color' => $theme_color,
  55. );
  56. if ( $description = get_bloginfo( 'description' ) ) {
  57. $manifest['description'] = $description;
  58. }
  59. $manifest['icons'] = array_map(
  60. array( $this, 'build_icon_object' ),
  61. Jetpack_PWA_Helpers::get_default_manifest_icon_sizes()
  62. );
  63. /**
  64. * Allow overriding the manifest.
  65. *
  66. * @since 5.6.0
  67. *
  68. * @param array $manifest
  69. */
  70. $manifest = apply_filters( 'jetpack_pwa_manifest', $manifest );
  71. wp_send_json( $manifest );
  72. }
  73. }
  74. function build_icon_object( $size ) {
  75. return array(
  76. 'src' => Jetpack_PWA_Helpers::site_icon_url( $size ),
  77. 'sizes' => sprintf( '%1$dx%1$d', $size ),
  78. );
  79. }
  80. }