PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.5.3
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.5.3
4.9.1 4.9.0 4.8.2 4.8.1 4.8.0 4.7.0 4.6.2 4.6.1 4.6.0 4.5.6 4.5.5 4.5.4 4.5.3 4.5.2 4.5.1 4.5.0 4.4.1 4.4.0 3.3.4 3.4.0 3.4.1 3.4.2 3.5.0 3.5.1 3.5.2 All 199 releases
betterdocs / includes / FrontEnd / SearchExtender.php

SearchExtender.php in BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot 4.5.3, at includes/FrontEnd/SearchExtender.php

68 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace WPDeveloper\BetterDocs\FrontEnd;
4
5 /**
6 * Extends WordPress search SQL on `docs` queries to also match docs whose
7 * assigned `doc_tag` or `doc_category` term names contain the search term.
8 *
9 * The filter is registered globally so it applies to every search query against
10 * the `docs` post type — including WP core's `GET /wp/v2/docs?search=...`,
11 * BetterDocs' `/betterdocs/v1/search`, and the shortcode/widget AJAX paths.
12 */
13 class SearchExtender {
14 public function __construct() {
15 add_filter( 'posts_search', [ $this, 'extend_search' ], 20, 2 );
16 }
17
18 /**
19 * Inject an OR clause that matches docs whose related taxonomy term names
20 * contain the search term.
21 *
22 * @param string $search The search SQL clause (already begins with " AND (").
23 * @param \WP_Query $query The WP_Query instance.
24 * @return string Modified search SQL.
25 */
26 public function extend_search( $search, $query ) {
27 global $wpdb;
28
29 if ( empty( $search ) ) {
30 return $search;
31 }
32
33 $post_type = isset( $query->query_vars['post_type'] ) ? $query->query_vars['post_type'] : '';
34 if ( is_array( $post_type ) ) {
35 if ( ! in_array( 'docs', $post_type, true ) ) {
36 return $search;
37 }
38 } elseif ( $post_type !== 'docs' ) {
39 return $search;
40 }
41
42 $search_term = isset( $query->query_vars['s'] ) ? (string) $query->query_vars['s'] : '';
43 if ( $search_term === '' ) {
44 return $search;
45 }
46
47 $taxonomies = [ 'doc_tag', 'doc_category' ];
48 $like = '%' . $wpdb->esc_like( $search_term ) . '%';
49
50 $placeholders = implode( ',', array_fill( 0, count( $taxonomies ), '%s' ) );
51 $args = $taxonomies;
52 $args[] = $like;
53
54 $subquery = $wpdb->prepare(
55 "{$wpdb->posts}.ID IN (
56 SELECT DISTINCT tr.object_id
57 FROM {$wpdb->term_relationships} tr
58 INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
59 INNER JOIN {$wpdb->terms} t ON tt.term_id = t.term_id
60 WHERE tt.taxonomy IN ({$placeholders}) AND t.name LIKE %s
61 )",
62 $args
63 );
64
65 return preg_replace( '/^\s*AND\s*\(/', " AND ({$subquery} OR ", $search, 1 );
66 }
67 }
68