Skip to content

Commit

Permalink
(fix): correctly extract URLs from shortcodes in 'links' field of pdc…
Browse files Browse the repository at this point in the history
…-item for REST API
  • Loading branch information
Mike van den Hoek authored and mvdhoek1 committed Jan 20, 2025
1 parent d0e32be commit 2eec584
Showing 1 changed file with 35 additions and 14 deletions.
49 changes: 35 additions & 14 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']) : '';
$shortcode = isset($link['pdc_links_shortcode']) ? wp_kses_post(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,39 @@ 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
* and the short is a URL itself.
*
* @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)) {
$url = esc_url($matches[1]);
} else {
$url = esc_url($shortcode);
}

return filter_var($url, FILTER_VALIDATE_URL) ?: '';
}

/**
* 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 2eec584

Please sign in to comment.