From b5557c2ccaf2ecca7099f32a093b7312f4ff38ff Mon Sep 17 00:00:00 2001 From: Maarten Bruna <14947039+ictbeheer@users.noreply.github.com> Date: Thu, 12 Jun 2025 16:46:30 +0200 Subject: [PATCH 1/2] (feat): utility functions for hierarchical post types --- src/PostData.php | 52 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/PostData.php b/src/PostData.php index 8f6efc1..fb15138 100644 --- a/src/PostData.php +++ b/src/PostData.php @@ -6,6 +6,7 @@ use Carbon\CarbonImmutable; use Corcel\Model\Post; +use Illuminate\Support\Collection; use ReflectionClass; use ReflectionNamedType; use RuntimeException; @@ -102,7 +103,7 @@ private static function dataClass(string $postType): string if (null === $classFQN) { return static::class; } - + if (! class_exists($classFQN)) { throw new RuntimeException(sprintf('The class "%s" does not exist or is not autoloaded.', $classFQN)); } @@ -292,4 +293,53 @@ public function url(): string return \get_permalink($this->id) ?: ''; } + + public function isTopLevelParent(): bool + { + return $this->hasChildren() && ! $this->isChild(); + } + + public function hasChildren(): bool + { + return $this->children()->isNotEmpty(); + } + + /** + * @param array $args + * + * @return Collection + * */ + public function children(array $args = []): Collection + { + if (! is_post_type_hierarchical($this->postType) || ! is_numeric($this->id)) { + return collect(); + } + $args = wp_parse_args($args, [ + 'post_parent' => $this->id, + 'post_type' => $this->postType, + 'order' => 'ASC', + 'orderby' => 'menu_order', + ]); + $children = get_children($args); + + return static::collect($children, Collection::class); + } + + public function isChild(): bool + { + return null !== $this->parent(); + } + + public function parent(): ?PostData + { + if (! is_post_type_hierarchical($this->postType) || ! is_numeric($this->id)) { + return null; + } + $parent = get_post_parent($this->id); + if (null === $parent) { + return null; + } + + return static::fromPost($parent); + } } From 8aa2da76db2c8086ec631df461b50ac0171177cb Mon Sep 17 00:00:00 2001 From: Maarten Bruna <14947039+ictbeheer@users.noreply.github.com> Date: Tue, 17 Jun 2025 17:31:04 +0200 Subject: [PATCH 2/2] (chore): rename method --- src/PostData.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PostData.php b/src/PostData.php index fb15138..e3a3eb2 100644 --- a/src/PostData.php +++ b/src/PostData.php @@ -296,10 +296,10 @@ public function url(): string public function isTopLevelParent(): bool { - return $this->hasChildren() && ! $this->isChild(); + return $this->isParent() && ! $this->isChild(); } - public function hasChildren(): bool + public function isParent(): bool { return $this->children()->isNotEmpty(); }