Files
wp-multi-city/includes/class-shortcode-dmr.php
T

68 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace WPMultiCity;
final class ShortcodeDmr
{
public const SHORTCODE = 'shortcode_dmr';
private static array $render_cache = [];
public static function reset_cache(): void
{
self::$render_cache = [];
}
public static function register(): void
{
\add_action('init', [self::class, 'do_register']);
}
public static function do_register(): void
{
\add_shortcode(self::SHORTCODE, [self::class, 'render']);
}
public static function render($atts = [], $content = null): string
{
$atts = \shortcode_atts(['id' => 0], (array) $atts);
$id = (int) $atts['id'];
if ($id <= 0) {
return '';
}
$town_slug = Helpers::current_town();
if ($town_slug === null) {
return '';
}
$cache_key = $id . '|' . $town_slug;
if (array_key_exists($cache_key, self::$render_cache)) {
return self::$render_cache[$cache_key];
}
$term = Helpers::get_term_by_slug($town_slug);
if ($term === null) {
return self::$render_cache[$cache_key] = '';
}
$rows = \get_field('list_shortcode', $id);
if (!is_array($rows) || $rows === []) {
return self::$render_cache[$cache_key] = '';
}
foreach ($rows as $row) {
if (!is_array($row) || !isset($row['town'])) {
continue;
}
if ((int) $row['town'] === (int) $term->term_id) {
$text = isset($row['text']) ? (string) $row['text'] : '';
return self::$render_cache[$cache_key] = $text;
}
}
return self::$render_cache[$cache_key] = '';
}
}