Skip to content

Commit

Permalink
feat: replace permalinks to posts that are redirected. (#1264)
Browse files Browse the repository at this point in the history
Co-authored-by: Sebastian Thulin <sebastian.thulin@helsingborg.se>
  • Loading branch information
sebastianthulin and Sebastian Thulin authored Jan 20, 2025
1 parent 78eb1ad commit 0c6043d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
3 changes: 3 additions & 0 deletions library/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,9 @@ public function __construct(
$decorator = new \Municipio\PostDecorators\ApplyProjectTerms($decorator);
$decorator = new \Municipio\PostDecorators\ApplyProjectProgress($this->wpService, $decorator);

//Seo Redirect
$decorator = new \Municipio\PostDecorators\ApplySeoRedirect($this->wpService, $decorator);

return $decorator->apply($post);
}, 10, 1);

Expand Down
40 changes: 40 additions & 0 deletions library/PostDecorators/ApplySeoRedirect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace Municipio\PostDecorators;

use WpService\Contracts\GetPostMeta;

/**
* ApplySeoRedirect class.
*
* This class is a PostDecorator implementation that replaces the permalink to the redirect URL if a redirect is set.
*/
class ApplySeoRedirect implements PostDecorator
{
/**
* @param GetPostMeta $wpService The WordPress service for retrieving post meta.
* @param PostDecorator|null $inner The inner post decorator. Defaults to a NullDecorator.
*/
public function __construct(private GetPostMeta $wpService, private ?PostDecorator $inner = new NullDecorator())
{
}

/**
* Applies the SEO redirect to the post.
*
* @param \WP_Post $post The post to replace the url for.
* @return \WP_Post The post with permalink replaced.
*/
public function apply(\WP_Post $post): \WP_Post
{
$post = $this->inner->apply($post);

$seoRedirectMetaUrl = $this->wpService->getPostMeta($post->ID, 'redirect', true);

if(filter_var($seoRedirectMetaUrl, FILTER_VALIDATE_URL)) {
$post->permalink = $seoRedirectMetaUrl;
}

return $post;
}
}

0 comments on commit 0c6043d

Please sign in to comment.