| 1 |
<?php |
| 2 |
|
| 3 |
namespace LPagery\controller; |
| 4 |
|
| 5 |
/** |
| 6 |
* Controller for handling taxonomy-related operations |
| 7 |
*/ |
| 8 |
class TaxonomyController |
| 9 |
{ |
| 10 |
private static $instance; |
| 11 |
|
| 12 |
/** |
| 13 |
* Singleton pattern implementation |
| 14 |
*/ |
| 15 |
public static function get_instance(): self |
| 16 |
{ |
| 17 |
if (null === self::$instance) { |
| 18 |
self::$instance = new self(); |
| 19 |
} |
| 20 |
return self::$instance; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Gets taxonomy terms |
| 25 |
* |
| 26 |
* @return array Taxonomy terms organized by taxonomy |
| 27 |
*/ |
| 28 |
public function getTaxonomyTerms(): array |
| 29 |
{ |
| 30 |
$categories = get_terms(array('hide_empty' => false, |
| 31 |
'orderby' => 'name', |
| 32 |
'order' => 'ASC')); |
| 33 |
|
| 34 |
$result = []; |
| 35 |
foreach ($categories as $category) { |
| 36 |
// Only add unique term IDs |
| 37 |
if (!isset($result[$category->taxonomy][$category->term_id])) { |
| 38 |
$result[$category->taxonomy][$category->term_id] = [ |
| 39 |
"id" => $category->term_id, |
| 40 |
"name" => $category->name |
| 41 |
]; |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// Reformat result to remove keys as term IDs |
| 46 |
foreach ($result as $taxonomy => $terms) { |
| 47 |
$result[$taxonomy] = array_values($terms); |
| 48 |
} |
| 49 |
|
| 50 |
return $result; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Gets taxonomies for a specific post type or all taxonomies |
| 55 |
* |
| 56 |
* @param string|null $post_type Post type to get taxonomies for |
| 57 |
* @return array Array of taxonomies |
| 58 |
*/ |
| 59 |
public function getTaxonomies(?string $post_type = null): array |
| 60 |
{ |
| 61 |
if (!$post_type) { |
| 62 |
$taxonomies = get_taxonomies(array(), 'objects'); |
| 63 |
} else { |
| 64 |
$taxonomies = get_object_taxonomies($post_type, 'objects'); |
| 65 |
} |
| 66 |
|
| 67 |
$result = array_map(function ($taxonomy) { |
| 68 |
return [ |
| 69 |
"name" => $taxonomy->name, |
| 70 |
"label" => $taxonomy->label != null ? $taxonomy->label : $taxonomy->name |
| 71 |
]; |
| 72 |
}, $taxonomies); |
| 73 |
|
| 74 |
return array_values($result); |
| 75 |
} |
| 76 |
} |