From a906e1b701e67e9ef21521ce5d7d236ac0c1aba6 Mon Sep 17 00:00:00 2001 From: peptiderepo Date: Fri, 24 Apr 2026 10:00:43 +0700 Subject: [PATCH] feat: add PR_Core_Internal_Posts_Provider implementation --- .../class-pr-core-internal-posts-provider.php | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 includes/core/class-pr-core-internal-posts-provider.php diff --git a/includes/core/class-pr-core-internal-posts-provider.php b/includes/core/class-pr-core-internal-posts-provider.php new file mode 100644 index 0000000..dc7bb49 --- /dev/null +++ b/includes/core/class-pr-core-internal-posts-provider.php @@ -0,0 +1,102 @@ + Array of WP_Post objects (may be empty). + */ + public function get_posts( int $peptide_id, int $limit ): array { + $peptide = get_post( $peptide_id ); + if ( ! $peptide || 'peptide' !== $peptide->post_type ) { + return []; + } + + $cache_key = 'pr_core_related_' . $peptide_id; + $cached = get_transient( $cache_key ); + if ( is_array( $cached ) ) { + return array_slice( $cached, 0, $limit ); + } + + // Primary: query posts tagged with peptide's slug as peptide_topic. + $posts = $this->query_by_taxonomy( $peptide->post_name, $limit ); + + // Fallback: if empty, search by peptide title. + if ( empty( $posts ) ) { + $posts = $this->query_by_search( $peptide->post_title, $limit ); + } + + // Cache for 1 hour. + set_transient( $cache_key, $posts, HOUR_IN_SECONDS ); + + return $posts; + } + + /** + * Query posts tagged with a specific peptide_topic term. + * + * @param string $peptide_slug The peptide's post_name (slug). + * @param int $limit Maximum posts to return. + * @return array + */ + private function query_by_taxonomy( string $peptide_slug, int $limit ): array { + $query = new WP_Query( [ + 'post_type' => 'post', + 'posts_per_page' => $limit, + 'orderby' => 'date', + 'order' => 'DESC', + 'tax_query' => [ + [ + 'taxonomy' => 'peptide_topic', + 'field' => 'slug', + 'terms' => $peptide_slug, + ], + ], + ] ); + + return $query->posts ?: []; + } + + /** + * Fallback: query posts by full-text search on post_title. + * + * @param string $search_term The peptide's display title. + * @param int $limit Maximum posts to return. + * @return array + */ + private function query_by_search( string $search_term, int $limit ): array { + $query = new WP_Query( [ + 'post_type' => 'post', + 'posts_per_page' => $limit, + 'orderby' => 'date', + 'order' => 'DESC', + 's' => $search_term, + ] ); + + return $query->posts ?: []; + } +}