Skip to content

Commit

Permalink
refactor: Restore wp_calculate_image_srcset callback.
Browse files Browse the repository at this point in the history
Adjust logic in image_source_srcset_replacement
  • Loading branch information
mindctrl committed Nov 13, 2023
1 parent f067fbe commit 8d96df2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
47 changes: 32 additions & 15 deletions plugins/faustwp/includes/replacement/callbacks.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ function image_source_replacement( $content ) {
return preg_replace( $patterns, "src=\"{$site_url}/", $content );
}

add_filter( 'wp_calculate_image_srcset', __NAMESPACE__ . '\\image_source_srcset_replacement' );
/**
* Callback for WordPress 'the_content' filter to replace paths to media.
*
Expand All @@ -97,23 +98,39 @@ function image_source_replacement( $content ) {
* @return string One or more arrays of source data.
*/
function image_source_srcset_replacement( $sources ) {
if ( is_image_source_replacement_enabled() ) {
$frontend_uri = faustwp_get_setting( 'frontend_uri' );
$site_url = site_url();

if ( is_array( $sources ) ) {
// For urls with no domain or the frontend domain, replace with the wp site_url.
$patterns = array(
"#^{$frontend_uri}/#",
'#^/#',
);
foreach ( $sources as $width => $source ) {
$sources[ $width ]['url'] = preg_replace( $patterns, "$site_url/", $sources[ $width ]['url'] );
}
}
$use_wp_domain_for_media = use_wp_domain_for_media();
$frontend_uri = faustwp_get_setting( 'frontend_uri' );
$site_url = site_url();

/**
* For urls with no domain or the frontend domain, replace with the WP site_url.
* This was the default replacement pattern until Faust 1.2, at which point this
* was adjusted to correct replacement bugs.
*/
$patterns = array(
"#^{$site_url}/#",
'#^/#',
);

return $sources;
$replacement = $frontend_uri;

/**
* If using WP domain for media and a frontend URL is encountered, rewrite it to WP URL.
*/
if ( $use_wp_domain_for_media ) {
$patterns = array(
"#^{$frontend_uri}/#",
'#^/#',
);
$replacement = $site_url;
}

if ( is_array( $sources ) ) {
foreach ( $sources as $width => $source ) {
$sources[ $width ]['url'] = preg_replace( $patterns, "$replacement/", $source['url'] );
}
}

return $sources;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ public function test_wpseo_xml_sitemap_post_url_filter() {
$this->assertSame( 10, has_action( 'wpseo_xml_sitemap_post_url', 'WPE\FaustWP\Replacement\yoast_sitemap_post_url' ) );
}

public function test_wp_calculate_image_srcset_filter(): void {
self::assertSame( 10, has_action( 'wp_calculate_image_srcset', 'WPE\FaustWP\Replacement\image_source_srcset_replacement' ) );
}

/**
* Tests content_replacement() returns original value when content replacement is not enabled.
*/
Expand Down

0 comments on commit 8d96df2

Please sign in to comment.