From a925aabc9cd0c1e29656cb9466ab1f2a6cab7c9d Mon Sep 17 00:00:00 2001 From: Jb Audras Date: Wed, 20 Jul 2022 21:11:30 +0000 Subject: [PATCH] Themes: Add a hook to filter theme header image URL. This changeset introduces the `get_header_image` filter, which can be used to modify header image URL returned by `get_header_image()`, in themes that support the Header Image feature. Props hztyfoon, audrasjb, mukesh27, SergeyBiryukov, costdev. Fixes #56180. git-svn-id: https://develop.svn.wordpress.org/trunk@53741 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/theme.php | 14 ++++++ tests/phpunit/tests/theme/customHeader.php | 53 ++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/wp-includes/theme.php b/src/wp-includes/theme.php index b52fb3ef7f..ef49f07e14 100644 --- a/src/wp-includes/theme.php +++ b/src/wp-includes/theme.php @@ -1179,6 +1179,20 @@ function get_header_image() { $url = get_random_header_image(); } + /** + * Filters the header image URL. + * + * @since 6.1.0 + * + * @param string $url Header image URL. + */ + $url = apply_filters( 'get_header_image', $url ); + + if ( ! is_string( $url ) ) { + return false; + } + + $url = trim( $url ); return sanitize_url( set_url_scheme( $url ) ); } diff --git a/tests/phpunit/tests/theme/customHeader.php b/tests/phpunit/tests/theme/customHeader.php index 958462afef..2005622b52 100644 --- a/tests/phpunit/tests/theme/customHeader.php +++ b/tests/phpunit/tests/theme/customHeader.php @@ -81,6 +81,59 @@ class Tests_Theme_CustomHeader extends WP_UnitTestCase { $this->assertFalse( $image ); } + /** + * Tests the "get_header_image" filter. + * + * @ticket 56180 + * + * @covers get_header_image + * + * @dataProvider data_filter_header_image + * + * @param mixed $header_image The header image. + * @param string $expected The expected return value from get_header_image(). + */ + public function test_filter_header_image( $header_image, $expected ) { + add_filter( + 'get_header_image', + static function() use ( $header_image ) { + return $header_image; + } + ); + + $this->assertSame( $expected, get_header_image() ); + } + + /** + * Data provider. + * + * @return array + */ + public function data_filter_header_image() { + return array( + 'an image url' => array( + 'header_image' => 'http://example.org/image.png', + 'expected' => 'http://example.org/image.png', + ), + 'an empty string' => array( + 'header_image' => '', + 'expected' => '', + ), + 'a string with spaces' => array( + 'header_image' => ' ', + 'expected' => '', + ), + 'null' => array( + 'header_image' => null, + 'expected' => false, + ), + 'false' => array( + 'header_image' => false, + 'expected' => false, + ), + ); + } + public function test_get_header_image_tag_without_registered_default_image() { $this->add_theme_support(); $html = get_header_image_tag();