diff --git a/src/Query/PostQuery.php b/src/Query/PostQuery.php index afd548b..7afb5b4 100644 --- a/src/Query/PostQuery.php +++ b/src/Query/PostQuery.php @@ -28,6 +28,29 @@ public function get(): Collection ->limit($this->attributes->limit()) ->offset($this->attributes->offset()); + /** + * Filters whether the current post should be excluded from query results. + * + * This applies when the query is not using a manual selection and the current post is not the configured sticky post. + * + * @param bool $excludeCurrentPost Whether to exclude the current post from the query results. Default true. + * + * @return bool Whether to exclude the current post from the query results. + */ + $excludeCurrentPost = apply_filters('yard_query_block_exclude_current_post', true); + + $currentPostId = $this->currentPostId(); + if ( + $excludeCurrentPost && + ! $this->attributes->hasManualSelection() && + ( + ! $this->attributes->hasStickyPost() || + $this->attributes->stickyPostID() !== $currentPostId + ) && + 0 < $currentPostId) { + $query->where('ID', '!=', $currentPostId); + } + if ($this->attributes->hasManualSelection()) { $query->whereIn('ID', $this->attributes->manualSelectionPostIDs()); } @@ -175,4 +198,17 @@ private function order(PostBuilder $query): PostBuilder return $query; } + + private function currentPostId(): int + { + if (function_exists('get_the_ID') && $id = get_the_ID()) { + return $id; + } + + if (function_exists('get_queried_object_id')) { + return get_queried_object_id(); + } + + return 0; + } }