Skip to content

Commit

Permalink
CDPT-2418 Remove trailing slash from document urls. (#805)
Browse files Browse the repository at this point in the history
* CDPT-2418 Remove trailing slash from document urls.

* Revert ingress change

* Update ingress.tpl.yml
  • Loading branch information
EarthlingDavey authored Jan 13, 2025
1 parent 1a79dca commit f66b8f1
Showing 1 changed file with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class WPDocumentRevisions

private $home_url = '';
private $site_url = '';
private $document_url_regex = '';
private $wp_document_revisions = null;

public function __construct()
Expand All @@ -28,13 +29,18 @@ public function __construct()
$this->site_url = get_site_url();
$this->home_url = get_home_url();

// Set the document URL regex - optional home_url, followed by /documents/.
$this->document_url_regex = '/^(' . preg_quote($this->home_url, '/') . ')?\/documents/';

// load hooks here, inside WP ecosys...
$this->hooks();
}

public function hooks(): void
{
add_filter('document_permalink', [$this, 'filterPermalink'], 10, 2);
// Filter to remove trailing slash from the document's URL.
add_filter('user_trailingslashit', [$this, 'filterTrailingSlash'], 10, 2);
// Filter using gzip, always return false, let nginx handle gzipping where necessary.
add_filter('document_serve_use_gzip', '__return_false', null, 2);
// Filter to retry missing files.
Expand All @@ -60,6 +66,29 @@ public function filterPermalink(string $link, null|object|array $document)
return str_replace($this->site_url, $this->home_url, $link);
}

/**
* Remove trailing slash from the document's URL.
*
* This is required because the site-wide permalink structure is set to include a trailing slash.
* Here, that default is overridden to remove the trailing slash for the document post type.
*
* This affects the URL in various places, e.g.
* - the document's URL on the document edit screen.
* - the URL for document downloads.
* - document URLs accessed with a trailing slash will be redirected to remove it.
*
* @param string $string The URL.
* @return string The filtered URL.
*/
public function filterTrailingSlash($string)
{
if (preg_match($this->document_url_regex, $string)) {
return untrailingslashit($string);
}

return $string;
}

/**
* Extract the date from the file path.
*
Expand Down Expand Up @@ -134,7 +163,7 @@ public function retryFilesNotFound($file, $attachment_id)

// Let's replace the date with the one from the attachment's guid.
$new_file = str_replace($dates['file'], $dates['guid'], $file);

// If the new file exists, return it.
if (is_file($new_file)) {
return $new_file;
Expand Down

0 comments on commit f66b8f1

Please sign in to comment.