| @@ -23,19 +23,48 @@ | ||
| 23 | 23 | add_action( |
| 24 | 24 | 'elementor/core/files/clear_cache', |
| 25 | 25 | fn() => $this->invalidate_cache(), |
| 26 | 26 | ); |
| 27 | + | |
| 28 | + add_filter( | |
| 29 | + 'elementor/document/related_posts', | |
| 30 | + fn( array $related, $post_id ) => $this->get_related_posts( $related, $post_id ), | |
| 31 | + 10, | |
| 32 | + 2 | |
| 33 | + ); | |
| 27 | 34 | } |
| 28 | 35 | |
| 29 | 36 | private function render_post( string $post_id ) { |
| 37 | + $component_ids = $this->get_component_ids_from_post_cached( $post_id ); | |
| 38 | + | |
| 39 | + $this->declare_components_rendered( $component_ids ); | |
| 40 | + } | |
| 41 | + | |
| 42 | + /** | |
| 43 | + * Handler for the `elementor/document/related_posts` filter. | |
| 44 | + * | |
| 45 | + * @param int[] $related Accumulated ids from previous filter handlers. | |
| 46 | + * @param string|int $post_id Parent post id being inspected. | |
| 47 | + * @return int[] Merged list of related post ids. | |
| 48 | + */ | |
| 49 | + private function get_related_posts( array $related, $post_id ): array { | |
| 50 | + $component_ids = $this->get_component_ids_from_post_cached( (string) $post_id ); | |
| 51 | + | |
| 52 | + return array_values( array_unique( array_merge( $related, array_map( 'intval', $component_ids ) ) ) ); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * Returns the component ids embedded in $post_id, reading from the | |
| 57 | + * traversal cache when available and writing to it otherwise. | |
| 58 | + * | |
| 59 | + * Both the render-action listener and the `elementor/document/related_posts` | |
| 60 | + * filter handler delegate here so the traversal logic lives in one place. | |
| 61 | + */ | |
| 62 | + private function get_component_ids_from_post_cached( string $post_id ): array { | |
| 30 | 63 | $cache_validity = new Cache_Validity(); |
| 31 | 64 | |
| 32 | 65 | if ( $cache_validity->is_valid( [ self::CACHE_ROOT_KEY, $post_id ] ) ) { |
| 33 | - $component_ids = $cache_validity->get_meta( [ self::CACHE_ROOT_KEY, $post_id ] ); | |
| 34 | - | |
| 35 | - $this->declare_components_rendered( $component_ids ); | |
| 36 | - | |
| 37 | - return; | |
| 66 | + return (array) $cache_validity->get_meta( [ self::CACHE_ROOT_KEY, $post_id ] ); | |
| 38 | 67 | } |
| 39 | 68 | |
| 40 | 69 | $components = $this->get_components_from_post( $post_id ); |
| 41 | 70 | $component_ids = Collection::make( $components ) |
| @@ -45,9 +74,9 @@ | ||
| 45 | 74 | ->all(); |
| 46 | 75 | |
| 47 | 76 | $cache_validity->validate( [ self::CACHE_ROOT_KEY, $post_id ], $component_ids ); |
| 48 | 77 | |
| 49 | - $this->declare_components_rendered( $component_ids ); | |
| 78 | + return $component_ids; | |
| 50 | 79 | } |
| 51 | 80 | |
| 52 | 81 | private function declare_components_rendered( array $post_ids ) { |
| 53 | 82 | foreach ( $post_ids as $post_id ) { |