page-level.php
67 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Output auto ads enabled code in head |
| 4 | * |
| 5 | * @var bool $privacy_enabled Whether to wait for user consent. |
| 6 | * @var bool $npa_enabled Whether to show non-personalized ads. |
| 7 | * @var string $client_id The Google AdSense client ID. |
| 8 | * @var bool $top_anchor AdSense anchor ad on top of pages. |
| 9 | * @var string $top_anchor_code The code for top anchor ads. |
| 10 | * @var string $script_src AdSense script url. |
| 11 | * @var bool $add_publisher_id Whether to add the publisher ID to the AdSense JavaScript URL. |
| 12 | */ |
| 13 | if ( $privacy_enabled ) : ?> |
| 14 | <script> |
| 15 | (function () { |
| 16 | var scriptDone = false; |
| 17 | document.addEventListener('advanced_ads_privacy', function (event) { |
| 18 | if ( |
| 19 | (event.detail.state !== 'accepted' && event.detail.state !== 'not_needed' && !advads.privacy.is_adsense_npa_enabled()) |
| 20 | || scriptDone |
| 21 | ) { |
| 22 | return; |
| 23 | } |
| 24 | // google adsense script can only be added once. |
| 25 | scriptDone = true; |
| 26 | |
| 27 | var script = document.createElement('script'), |
| 28 | first = document.getElementsByTagName('script')[0]; |
| 29 | |
| 30 | script.async = true; |
| 31 | script.crossOrigin = 'anonymous'; |
| 32 | script.src = '<?php echo esc_url( $script_src ); ?>'; |
| 33 | <?php |
| 34 | if ( $top_anchor ) { |
| 35 | // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- relevant user input has already been escaped. |
| 36 | echo $top_anchor_code; |
| 37 | } elseif ( ! $add_publisher_id ) { |
| 38 | printf( 'script.dataset.adClient = "%s";', esc_attr( $client_id ) ); |
| 39 | } |
| 40 | ?> |
| 41 | |
| 42 | first.parentNode.insertBefore(script, first); |
| 43 | }); |
| 44 | })(); |
| 45 | </script> |
| 46 | <?php |
| 47 | return; |
| 48 | endif; |
| 49 | // Privacy not enabled. |
| 50 | // phpcs:disable WordPress.WP.EnqueuedResources |
| 51 | if ( $top_anchor ) { |
| 52 | printf( |
| 53 | '<script async src="%s"></script><script>%s</script>', |
| 54 | esc_attr( $script_src ), |
| 55 | // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- the snippet has already been escaped. |
| 56 | $top_anchor_code |
| 57 | ); |
| 58 | } else { |
| 59 | // Don't add the data-ad-client attribute when the publisher ID is appended to the script URL. |
| 60 | printf( |
| 61 | '<script %s async src="%s" crossorigin="anonymous"></script>', |
| 62 | ! $add_publisher_id ? 'data-ad-client="' . esc_attr( $client_id ) . '"' : '', |
| 63 | esc_url( $script_src ) |
| 64 | ); |
| 65 | } |
| 66 | // phpcs:enable |
| 67 |