Skip to content

Commit

Permalink
fix: correctly extract URLs from shortcodes in 'links' field of pdc-i…
Browse files Browse the repository at this point in the history
…tem for REST API
  • Loading branch information
Mike van den Hoek committed Jan 10, 2025
1 parent d0e32be commit a70b38c
Showing 1 changed file with 31 additions and 13 deletions.
44 changes: 31 additions & 13 deletions src/Base/RestAPI/ItemFields/LinksField.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<?php

/**
* Adds link fields to the output.
*/

namespace OWC\PDC\Base\RestAPI\ItemFields;

use WP_Post;
use OWC\PDC\Base\Support\CreatesFields;
use WP_Post;

/**
* Adds link fields to the output.
Expand All @@ -15,18 +16,15 @@ class LinksField extends CreatesFields
{
/**
* Generate the links field.
*
* @param WP_Post $post
*
* @return array
*/
public function create(WP_Post $post): array
{
return array_map(function ($link) {
$shortcode = isset($link['pdc_links_shortcode']) ? do_shortcode($link['pdc_links_shortcode']) : '';
$url = isset($link['pdc_links_url']) ? esc_url($link['pdc_links_url']) : '';

if (! empty($shortcode)) {
$url = $shortcode;
$url = $this->handlePossibleUrlInShortcode($shortcode);
}

return [
Expand All @@ -37,16 +35,36 @@ public function create(WP_Post $post): array
}

/**
* Get links of a post, if URL & title are present.
* Extract a URL from a shortcode or return the shortcode itself if no URL is found.
*
* @param WP_Post $post
*
* @return array
* Some shortcodes may contain a URL embedded within an HTML element, such as an
* <a> tag. This method attempts to extract the URL from the `href` attribute
* using a regular expression. If no valid `href` is found, the raw shortcode
* string is sanitized and returned as a fallback.
*/
private function handlePossibleUrlInShortcode(string $shortcode): string
{
$regex = '/href=["\']([^"\']+)["\']/';

if (preg_match($regex, $shortcode, $matches)) {
return esc_url($matches[1]);
}

return esc_url($shortcode);
}

/**
* Get links of a post, if URL & title are present.
*/
private function getLinks(WP_Post $post)
private function getLinks(WP_Post $post): array
{
return array_filter(get_post_meta($post->ID, '_owc_pdc_links_group', true) ?: [], function ($link) {
return (! empty($link['pdc_links_url']) or ! empty($link['pdc_links_shortcode'])) && (! empty($link['pdc_links_title']));
$links = get_post_meta($post->ID, '_owc_pdc_links_group', true) ?: [];

return array_filter($links, function ($link) {
$hasUrlOrShortcode = ! empty($link['pdc_links_url']) || ! empty($link['pdc_links_shortcode']);
$hasTitle = ! empty($link['pdc_links_title']);

return $hasUrlOrShortcode && $hasTitle;
});
}
}

0 comments on commit a70b38c

Please sign in to comment.