PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.2.6
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.2.6
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
← All changes | includes/Core/Query.php +1110 -1394 4.9.14.2.6 View file →
@@ -1,14 +1,8 @@
1 1 <?php
2 -// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query,WordPress.DB.SlowDBQuery.slow_db_query_tax_query,WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- core docs query builder; meta/tax filtering required for docs/category/KB filtering.
3 -// phpcs:disable WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude -- excludes are user-driven (settings UI) and part of the query builder's public contract.
2 +
4 3 namespace WPDeveloper\BetterDocs\Core;
5 4
6 -if ( ! defined( 'ABSPATH' ) ) {
7 - exit;
8 -}
9 -
10 -
11 5 use WP_Query;
12 6 use WPDeveloper\BetterDocs\Utils\Base;
13 7 use WPDeveloper\BetterDocs\Utils\Database;
14 8 use WPDeveloper\BetterDocs\Dependencies\DI\Container;
@@ -13,1358 +7,1089 @@
13 7 use WPDeveloper\BetterDocs\Utils\Database;
14 8 use WPDeveloper\BetterDocs\Dependencies\DI\Container;
15 9
16 10 class Query extends Base {
17 - private $container;
18 - protected $database;
19 - protected $settings;
11 + private $container;
12 + protected $database;
13 + protected $settings;
20 14
21 - public function __construct( Container $container, Database $database, Settings $settings ) {
22 - $this->container = $container;
23 - $this->database = $database;
24 - $this->settings = $settings;
15 + public function __construct( Container $container, Database $database, Settings $settings ) {
16 + $this->container = $container;
17 + $this->database = $database;
18 + $this->settings = $settings;
25 19
26 - add_action( 'parse_term_query', array( $this, 'parse_term_query' ) );
27 - // add_action( 'parse_query', [$this, 'parse_query'], 1 );
28 - add_action( 'pre_get_posts', array( $this, 'pre_get_posts' ), 1 );
29 - add_filter( 'betterdocs_base_terms_args', array( $this, 'modify_terms_args_for_private_docs' ), 10, 1 );
30 - // Drops terms whose private-inclusive count is 0 after `hide_empty` was
31 - // turned off by modify_terms_args_for_private_docs().
32 - add_filter( 'get_terms', array( $this, 'filter_terms_for_private_docs' ), 10, 3 );
20 + add_action( 'parse_term_query', [ $this, 'parse_term_query' ] );
21 + // add_action( 'parse_query', [$this, 'parse_query'], 1 );
22 + add_action( 'pre_get_posts', [ $this, 'pre_get_posts' ], 1 );
23 + add_filter( 'betterdocs_base_terms_args', [ $this, 'modify_terms_args_for_private_docs' ], 10, 1 );
33 24
34 - // Invalidate cached doc-category counts on any write that could change them.
35 - add_action( 'save_post_docs', array( $this, 'flush_term_counts_cache' ) );
36 - add_action( 'deleted_post', array( $this, 'flush_term_counts_cache_on_post' ), 10, 2 );
37 - add_action( 'edited_doc_category', array( $this, 'flush_term_counts_cache' ) );
38 - add_action( 'created_doc_category', array( $this, 'flush_term_counts_cache' ) );
39 - add_action( 'delete_doc_category', array( $this, 'flush_term_counts_cache' ) );
40 - add_action( 'set_object_terms', array( $this, 'flush_term_counts_cache_on_set' ), 10, 4 );
25 + /**
26 + * These below filters are hooked for navigation only.
27 + *
28 + * For old version of this portion.
29 + * @see `betterdocs_single_post_nav` filter
30 + *
31 + * For details:
32 + * @see https://developer.wordpress.org/reference/functions/get_next_post/
33 + * @see https://developer.wordpress.org/reference/functions/get_previous_post/
34 + *
35 + * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
36 + */
37 + add_filter( 'get_next_post_where', [ $this, 'next_post_where' ], 99, 5 );
38 + add_filter( 'get_previous_post_where', [ $this, 'previous_post_where' ], 99, 5 );
41 39
42 - /**
43 - * These below filters are hooked for navigation only.
44 - *
45 - * For old version of this portion.
46 - * @see `betterdocs_single_post_nav` filter
47 - *
48 - * For details:
49 - * @see https://developer.wordpress.org/reference/functions/get_next_post/
50 - * @see https://developer.wordpress.org/reference/functions/get_previous_post/
51 - *
52 - * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
53 - */
54 - add_filter( 'get_next_post_where', array( $this, 'next_post_where' ), 99, 5 );
55 - add_filter( 'get_previous_post_where', array( $this, 'previous_post_where' ), 99, 5 );
40 + $this->init();
56 41
57 - $this->init();
42 + /**
43 + * Modify Popular Docs Query (For Shortcode & Widget)
44 + */
45 + add_filter( 'posts_clauses', [ $this, 'mod_query_popular_docs' ], 10, 2 );
46 + }
58 47
59 - /**
60 - * Modify Popular Docs Query (For Shortcode & Widget)
61 - */
62 - add_filter( 'posts_clauses', array( $this, 'mod_query_popular_docs' ), 10, 2 );
63 - }
48 + public function mod_query_popular_docs( $clauses, $wp_query ) {
49 + if ( isset( $wp_query->query['meta_key'] ) ) {
50 + if ( $wp_query->query['meta_key'] == '_betterdocs_meta_views' ) {
51 + global $wpdb;
52 + $order = isset( $wp_query->query['order'] ) ? $wp_query->query['order'] : '';
53 + $order_by_query = ( $order == 'ASC' || $order == 'DESC' ) ? "SUM({$wpdb->prefix}betterdocs_analytics.impressions) {$order}" : ( $order == 'MODIFIED' ? "{$wpdb->prefix}posts.post_modified_gmt DESC" : "{$wpdb->prefix}posts.post_date_gmt DESC" );
54 + $clauses['join'] = "JOIN {$wpdb->prefix}betterdocs_analytics ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}betterdocs_analytics.post_id";
55 + $clauses['where'] = ! current_user_can( 'read_private_docs' ) ? "AND ( ( {$wpdb->prefix}posts.post_type = 'docs' ) AND ( {$wpdb->prefix}posts.post_status = 'publish' OR {$wpdb->prefix}posts.post_status = 'future' ) )" : "AND ( ( {$wpdb->prefix}posts.post_type = 'docs' ) AND ( {$wpdb->prefix}posts.post_status = 'publish' OR {$wpdb->prefix}posts.post_status = 'future' OR {$wpdb->prefix}posts.post_status = 'draft' OR {$wpdb->prefix}posts.post_status = 'pending' OR {$wpdb->prefix}posts.post_status = 'private' ) )";
56 + $clauses['orderby'] = $order_by_query;
57 + $clauses['groupby'] = "{$wpdb->prefix}betterdocs_analytics.post_id";
58 + if ( is_plugin_active( 'sitepress-multilingual-cms/sitepress.php' ) ) {
59 + global $sitepress;
60 + if ( $sitepress->is_setup_complete() ) {
61 + $constant_language_code = ICL_LANGUAGE_CODE;
62 + $clauses['join'] .= " JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id";
63 + $clauses['where'] .= " AND ( {$wpdb->prefix}icl_translations.language_code = '{$constant_language_code}' ) AND ( {$wpdb->prefix}icl_translations.element_type = CONCAT('post_', {$wpdb->prefix}posts.post_type ) )";
64 + }
65 + }
66 + }
67 + }
68 + return $clauses;
69 + }
64 70
65 - public function mod_query_popular_docs( $clauses, $wp_query ) {
66 - if ( isset( $wp_query->query[ 'meta_key' ] ) ) {
67 - if ( '_betterdocs_meta_views' == $wp_query->query[ 'meta_key' ] ) {
68 - global $wpdb;
69 - $order = isset( $wp_query->query[ 'order' ] ) ? $wp_query->query[ 'order' ] : '';
70 - $order_by_query = ( 'ASC' == $order || 'DESC' == $order ) ? "SUM({$wpdb->prefix}betterdocs_analytics.impressions) {$order}" : ( 'MODIFIED' == $order ? "{$wpdb->prefix}posts.post_modified_gmt DESC" : "{$wpdb->prefix}posts.post_date_gmt DESC" );
71 - $clauses[ 'join' ] = "JOIN {$wpdb->prefix}betterdocs_analytics ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}betterdocs_analytics.post_id";
72 - $clauses[ 'where' ] = ! current_user_can( 'read_private_docs' ) ? "AND ( ( {$wpdb->prefix}posts.post_type = 'docs' ) AND ( {$wpdb->prefix}posts.post_status = 'publish' OR {$wpdb->prefix}posts.post_status = 'future' ) )" : "AND ( ( {$wpdb->prefix}posts.post_type = 'docs' ) AND ( {$wpdb->prefix}posts.post_status = 'publish' OR {$wpdb->prefix}posts.post_status = 'future' OR {$wpdb->prefix}posts.post_status = 'draft' OR {$wpdb->prefix}posts.post_status = 'pending' OR {$wpdb->prefix}posts.post_status = 'private' ) )";
73 - $clauses[ 'orderby' ] = $order_by_query;
74 - $clauses[ 'groupby' ] = "{$wpdb->prefix}betterdocs_analytics.post_id";
75 - if ( is_plugin_active( 'sitepress-multilingual-cms/sitepress.php' ) ) {
76 - global $sitepress;
77 - if ( $sitepress->is_setup_complete() ) {
78 - $constant_language_code = ICL_LANGUAGE_CODE;
79 - $clauses[ 'join' ] .= " JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id";
80 - $clauses[ 'where' ] .= " AND ( {$wpdb->prefix}icl_translations.language_code = '{$constant_language_code}' ) AND ( {$wpdb->prefix}icl_translations.element_type = CONCAT('post_', {$wpdb->prefix}posts.post_type ) )";
81 - }
82 - }
83 - }
84 - }
85 - return $clauses;
86 - }
71 + public function init() {
72 + }
87 73
88 - public function init() {
89 - }
74 + /**
75 + * Modify terms args to include terms with only private docs for users with read_private_docs capability
76 + *
77 + * @param array $args
78 + * @return array
79 + */
80 + public function modify_terms_args_for_private_docs( $args ) {
81 + // Only modify for users with read_private_docs capability and supported taxonomies
82 + if ( ! current_user_can( 'read_private_docs' ) || ! isset( $args['taxonomy'] ) ) {
83 + return $args;
84 + }
90 85
91 - /**
92 - * Modify terms args to include terms whose only docs are private, for users allowed to read them.
93 - *
94 - * Gated on being logged in rather than on `read_private_docs`, because a doc's own
95 - * author may read their private doc without holding that capability. Which docs
96 - * actually count is decided per post by can_read_doc().
97 - *
98 - * @param array $args
99 - * @return array
100 - */
101 - public function modify_terms_args_for_private_docs( $args ) {
102 - // Logged-out visitors always get WordPress' stock `hide_empty` behaviour.
103 - if ( ! is_user_logged_in() || ! isset( $args[ 'taxonomy' ] ) ) {
104 - return $args;
105 - }
86 + // Only support doc_category taxonomy for private docs filtering
87 + // knowledge_base terms don't have docs directly assigned to them
88 + $supported_taxonomies = ['doc_category'];
89 + if ( ! in_array( $args['taxonomy'], $supported_taxonomies ) ) {
90 + return $args;
91 + }
106 92
107 - /**
108 - * Let add-ons opt their own taxonomies into the private-docs rescue path.
109 - *
110 - * BetterDocs Pro hooks this for `knowledge_base` (Multiple KB), where docs
111 - * ARE assigned to the KB term directly.
112 - *
113 - * @param array $args Term query args.
114 - */
115 - $_filtered = apply_filters( 'betterdocs_modify_terms_args_for_private_docs', $args );
116 - if ( is_array( $_filtered ) ) {
117 - $args = $_filtered;
118 - }
93 + // If hide_empty is true, we need to modify the logic to include terms with private docs
94 + if ( isset( $args['hide_empty'] ) && $args['hide_empty'] ) {
95 + // Set hide_empty to false and we'll filter manually later
96 + $args['hide_empty'] = false;
97 + // Add a flag to indicate we need to filter manually
98 + $args['_betterdocs_filter_private'] = true;
99 + }
119 100
120 - // Already handled by an add-on (e.g. Pro's Multiple KB).
121 - if ( ! empty( $args[ '_betterdocs_filter_private' ] ) ) {
122 - return $args;
123 - }
101 + return $args;
102 + }
124 103
125 - /**
126 - * Taxonomies whose terms have docs assigned directly, so a private-inclusive
127 - * object count can rescue a term WordPress dropped for `hide_empty`.
128 - *
129 - * `knowledge_base` is included so a KB whose only docs are private still shows
130 - * up for privileged users even on older Pro builds that predate the filter above.
131 - */
132 - $supported_taxonomies = array( 'doc_category', 'knowledge_base' );
133 - if ( ! in_array( $args[ 'taxonomy' ], $supported_taxonomies, true ) ) {
134 - return $args;
135 - }
104 + public function parse_term_query( $term_query ) {
105 + if ( empty( $term_query->query_vars['taxonomy'] ) ) {
106 + return;
107 + }
136 108
137 - // If hide_empty is true, we need to modify the logic to include terms with private docs
138 - if ( isset( $args[ 'hide_empty' ] ) && $args[ 'hide_empty' ] ) {
139 - // Set hide_empty to false and we'll filter manually later
140 - $args[ 'hide_empty' ] = false;
141 - // Add a flag to indicate we need to filter manually
142 - $args[ '_betterdocs_filter_private' ] = true;
143 - }
109 + if ( ! in_array( 'doc_category', $term_query->query_vars['taxonomy'], true ) ) {
110 + return;
111 + }
144 112
145 - return $args;
146 - }
113 + global $current_screen;
147 114
148 - public function parse_term_query( $term_query ) {
149 - if ( empty( $term_query->query_vars[ 'taxonomy' ] ) ) {
150 - return;
151 - }
115 + if ( $current_screen == null ) {
116 + return;
117 + }
152 118
153 - if ( ! in_array( 'doc_category', $term_query->query_vars[ 'taxonomy' ], true ) ) {
154 - return;
155 - }
119 + if ( $current_screen->taxonomy !== 'doc_category' || $current_screen->id != 'edit-doc_category' ) {
120 + return;
121 + }
156 122
157 - global $current_screen;
123 + // Use base meta key for admin listing - fallback logic is handled in set_tax_order
124 + $meta_key = 'doc_category_order';
158 125
159 - if ( null == $current_screen ) {
160 - return;
161 - }
126 + $term_query->query_vars['meta_query'] = [
127 + [
128 + 'key' => $meta_key,
129 + 'type' => 'NUMERIC'
130 + ]
131 + ];
162 132
163 - if ( 'doc_category' !== $current_screen->taxonomy || 'edit-doc_category' != $current_screen->id ) {
164 - return;
165 - }
133 + $term_query->query_vars['orderby'] = 'meta_value_num';
134 + }
166 135
167 - // Use base meta key for admin listing - fallback logic is handled in set_tax_order
168 - $meta_key = 'doc_category_order';
136 + public function parse_query( &$query ) {
137 + // dump( is_single(), $query->query_vars );
138 + // if ( is_single() && isset( $query->query_vars['post_type'] ) && $query->query_vars['post_type'] == 'docs' ) {
139 + // $query->is_single = false;
140 + // $query->is_archive = true;
141 + // $query->set( 'knowledge_base', $query->query_vars['docs'] );
142 + // }
143 + }
169 144
170 - $term_query->query_vars[ 'meta_query' ] = array(
171 - array(
172 - 'key' => $meta_key,
173 - 'type' => 'NUMERIC'
174 - )
175 - );
145 + public function pre_get_posts( &$query ) {
146 + if ( is_admin() || ! $query->is_main_query() ) {
147 + return;
148 + }
176 149
177 - $term_query->query_vars[ 'orderby' ] = 'meta_value_num';
178 - }
150 + if ( is_tax( 'doc_category' ) ) {
151 + $query->set( 'post_type', 'docs' );
152 + $query->set( 'posts_per_archive_page', -1 );
179 153
180 - public function parse_query( &$query ) {
181 - // dump( is_single(), $query->query_vars );
182 - // if ( is_single() && isset( $query->query_vars['post_type'] ) && $query->query_vars['post_type'] == 'docs' ) {
183 - // $query->is_single = false;
184 - // $query->is_archive = true;
185 - // $query->set( 'knowledge_base', $query->query_vars['docs'] );
186 - // }
187 - }
154 + $term = get_term_by( 'slug', $query->get( 'doc_category', '' ), 'doc_category' );
188 155
189 - public function pre_get_posts( &$query ) {
190 - if ( is_admin() || ! $query->is_main_query() ) {
191 - return;
192 - }
156 + if ( $term && isset( $term->term_id ) ) {
157 + $post__in = $this->get_docs_order_by_terms( $term->term_id );
158 + } else {
159 + $post__in = [];
160 + }
161 + if ( ! empty( $post__in ) ) {
162 + $query->set( 'orderby', 'post__in' );
163 + $query->set( 'post__in', $post__in );
164 + }
193 165
194 - if ( is_tax( 'doc_category' ) ) {
195 - $query->set( 'post_type', 'docs' );
196 - $query->set( 'posts_per_archive_page', -1 );
166 + // if ( ! empty( $query->query_vars['knowledge_base'] ) ) {
167 + // $query->betterdocs_terms = get_terms( [
168 + // 'taxonomy' => 'doc_category',
169 + // 'parent' => 0,
170 + // 'hide_empty' => true,
171 + // 'meta_query' => [
172 + // 'relation' => 'OR',
173 + // [
174 + // 'key' => 'doc_category_knowledge_base',
175 + // 'value' => $query->query_vars['knowledge_base'],
176 + // 'compare' => 'LIKE'
177 + // ]
178 + // ]
179 + // ] );
180 + // }
181 + }
197 182
198 - $term = get_term_by( 'slug', $query->get( 'doc_category', '' ), 'doc_category' );
183 + // dump( is_archive(), $query->query_vars );
184 + }
199 185
200 - if ( $term && isset( $term->term_id ) ) {
201 - $post__in = $this->get_docs_order_by_terms( $term->term_id );
202 - } else {
203 - $post__in = array();
204 - }
205 - if ( ! empty( $post__in ) ) {
206 - $query->set( 'orderby', 'post__in' );
207 - $query->set( 'post__in', $post__in );
208 - }
186 + /**
187 + * Get docs orders by term_id.
188 + *
189 + * @since 2.5.0
190 + * @param int $term_id
191 + *
192 + * @return array
193 + */
194 + public function get_docs_order_by_terms( $term_id ) {
195 + global $wpdb;
209 196
210 - // if ( ! empty( $query->query_vars['knowledge_base'] ) ) {
211 - // $query->betterdocs_terms = get_terms( [
212 - // 'taxonomy' => 'doc_category',
213 - // 'parent' => 0,
214 - // 'hide_empty' => true,
215 - // 'meta_query' => [
216 - // 'relation' => 'OR',
217 - // [
218 - // 'key' => 'doc_category_knowledge_base',
219 - // 'value' => $query->query_vars['knowledge_base'],
220 - // 'compare' => 'LIKE'
221 - // ]
222 - // ]
223 - // ] );
224 - // }
225 - }
197 + // Get language-specific meta key with fallback
198 + $meta_key = \WPDeveloper\BetterDocs\Utils\Helper::get_meta_key_with_fallback( '_docs_order', $term_id );
199 + $_docs_order = get_term_meta( $term_id, $meta_key, true );
226 200
227 - // dump( is_archive(), $query->query_vars );
228 - }
201 + $query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}term_relationships WHERE term_taxonomy_id = %d", $term_id );
202 + $query_key = "docs_order_by_terms_{$term_id}_{$meta_key}_" . md5( $query );
229 203
230 - /**
231 - * Get docs orders by term_id.
232 - *
233 - * @since 2.5.0
234 - * @param int $term_id
235 - *
236 - * @return array
237 - */
238 - public function get_docs_order_by_terms( $term_id ) {
239 - global $wpdb;
204 + if ( ( $results = $this->database->get_cache( $query_key ) ) !== false ) {
205 + return $results;
206 + }
240 207
241 - // Get language-specific meta key with fallback
242 - $meta_key = \WPDeveloper\BetterDocs\Utils\Helper::get_meta_key_with_fallback( '_docs_order', $term_id );
243 - $_docs_order = get_term_meta( $term_id, $meta_key, true );
208 + if ( ! empty( $_docs_order ) ) {
209 + $_docs_order = explode( ',', $_docs_order );
210 + $new_ids = [];
244 211
245 - $query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}term_relationships WHERE term_taxonomy_id = %d", $term_id );
246 - $query_key = "docs_order_by_terms_{$term_id}_{$meta_key}_" . md5( $query );
212 + $results = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
247 213
248 - if ( ( $results = $this->database->get_cache( $query_key ) ) !== false ) {
249 - return $results;
250 - }
214 + if ( is_array( $results ) && ! empty( $results ) ) {
215 + $object_ids = array_filter(
216 + $results,
217 + function ( $value ) use ( $_docs_order ) {
218 + return ! in_array( $value->object_id, $_docs_order );
219 + }
220 + );
251 221
252 - if ( ! empty( $_docs_order ) ) {
253 - $_docs_order = explode( ',', $_docs_order );
254 - $new_ids = array();
222 + if ( ! empty( $object_ids ) ) {
223 + array_walk(
224 + $object_ids,
225 + function ( $value ) use ( &$new_ids ) {
226 + $new_ids[] = $value->object_id;
227 + }
228 + );
229 + }
230 + }
255 231
256 - // $query is prepared upstream; results are cached via $this->database->get_cache above (line 210).
257 - $results = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
232 + $_docs_order = array_merge( $new_ids, $_docs_order );
233 + $this->database->set_cache( $query_key, $_docs_order, 1 );
258 234
259 - if ( is_array( $results ) && ! empty( $results ) ) {
260 - $object_ids = array_filter(
261 - $results,
262 - function ( $value ) use ( $_docs_order ) {
263 - return ! in_array( $value->object_id, $_docs_order );
264 - }
265 - );
235 + return $_docs_order;
236 + }
266 237
267 - if ( ! empty( $object_ids ) ) {
268 - array_walk(
269 - $object_ids,
270 - function ( $value ) use ( &$new_ids ) {
271 - $new_ids[ ] = $value->object_id;
272 - }
273 - );
274 - }
275 - }
238 + return [];
239 + }
276 240
277 - $_docs_order = array_merge( $new_ids, $_docs_order );
278 - $this->database->set_cache( $query_key, $_docs_order, 1 );
241 + /**
242 + * For determine the next post ID
243 + *
244 + * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
245 + *
246 + * @param mixed $where
247 + * @param mixed $in_same_term
248 + * @param mixed $excluded_terms
249 + * @param mixed $taxonomy
250 + * @param mixed $post
251 + * @return mixed
252 + */
253 + public function next_post_where( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) {
254 + return $this->get_adjacent_post_id( 'next', $where, $post, $taxonomy );
255 + }
279 256
280 - return $_docs_order;
281 - }
257 + /**
258 + * For determine the previous post ID
259 + *
260 + * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
261 + *
262 + * @param mixed $where
263 + * @param mixed $in_same_term
264 + * @param mixed $excluded_terms
265 + * @param mixed $taxonomy
266 + * @param mixed $post
267 + * @return mixed
268 + */
269 + public function previous_post_where( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) {
270 + return $this->get_adjacent_post_id( 'previous', $where, $post, $taxonomy );
271 + }
282 272
283 - return array();
284 - }
273 + /**
274 + * Get where clause for next/previous post ID mainly used in post navigation.
275 + *
276 + * @see `previous_post_where` and `next_post_where` methods.
277 + *
278 + * @param mixed $adjacent
279 + * @param mixed $where
280 + * @param mixed $post
281 + * @param mixed $taxonomy
282 + * @return mixed
283 + */
284 + private function get_adjacent_post_id( $adjacent, $where, $post, $taxonomy ) {
285 + if ( $taxonomy !== 'doc_category' ) {
286 + return $where;
287 + }
285 288
286 - /**
287 - * For determine the next post ID
288 - *
289 - * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
290 - *
291 - * @param mixed $where
292 - * @param mixed $in_same_term
293 - * @param mixed $excluded_terms
294 - * @param mixed $taxonomy
295 - * @param mixed $post
296 - * @return mixed
297 - */
298 - public function next_post_where( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) {
299 - return $this->get_adjacent_post_id( 'next', $where, $post, $taxonomy );
300 - }
289 + $_id = null;
290 + $_terms = get_the_terms( $post->ID, 'doc_category' );
291 + if ( empty( $_terms ) ) {
292 + return $where;
293 + }
301 294
302 - /**
303 - * For determine the previous post ID
304 - *
305 - * @link https://developer.wordpress.org/reference/hooks/get_adjacent_post_where/
306 - *
307 - * @param mixed $where
308 - * @param mixed $in_same_term
309 - * @param mixed $excluded_terms
310 - * @param mixed $taxonomy
311 - * @param mixed $post
312 - * @return mixed
313 - */
314 - public function previous_post_where( $where, $in_same_term, $excluded_terms, $taxonomy, $post ) {
315 - return $this->get_adjacent_post_id( 'previous', $where, $post, $taxonomy );
316 - }
295 + global $wp_query, $wpdb;
317 296
318 - /**
319 - * Get where clause for next/previous post ID mainly used in post navigation.
320 - *
321 - * @see `previous_post_where` and `next_post_where` methods.
322 - *
323 - * @param mixed $adjacent
324 - * @param mixed $where
325 - * @param mixed $post
326 - * @param mixed $taxonomy
327 - * @return mixed
328 - */
329 - private function get_adjacent_post_id( $adjacent, $where, $post, $taxonomy ) {
330 - if ( 'doc_category' !== $taxonomy ) {
331 - return $where;
332 - }
297 + $_docs_order = $this->get_docs_order_by_terms( $_terms[0]->term_id );
333 298
334 - $_id = null;
335 - $_terms = get_the_terms( $post->ID, 'doc_category' );
336 - if ( empty( $_terms ) ) {
337 - return $where;
338 - }
299 + $_where = explode( 'AND', $where );
300 + if ( is_array( $_where ) ) {
301 + // $_where[0] = str_replace( 'WHERE ', '', $_where[0] );
302 + unset( $_where[0] );
303 + $_where = implode( 'AND', $_where );
304 + }
339 305
340 - global $wp_query, $wpdb;
306 + $_orderby = $this->settings->get( 'alphabetically_order_post', 'betterdocs_order' );
307 + $_order = $this->settings->get( 'docs_order', 'ASC' );
308 + $_docs_order = $_orderby === 'betterdocs_order' ? $_docs_order : [];
341 309
342 - $_docs_order = $this->get_docs_order_by_terms( $_terms[ 0 ]->term_id );
310 + if ( empty( $_docs_order ) ) {
311 + $statuses = [ 'publish' ];
343 312
344 - $_orderby = $this->settings->get( 'alphabetically_order_post', 'betterdocs_order' );
345 - $_order = $this->settings->get( 'docs_order', 'ASC' );
346 - $_docs_order = 'betterdocs_order' === $_orderby ? $_docs_order : array();
313 + if ( current_user_can( 'read_private_docs' ) ) {
314 + $statuses[] = 'private';
315 + }
347 316
348 - if ( empty( $_docs_order ) ) {
349 - $statuses = array( 'publish' );
317 + $_args = [
318 + 'post_status' => $statuses
319 + ];
320 + if ( isset( $wp_query->query_vars['doc_category'] ) ) {
321 + $_args['tax_query'][] = [
322 + 'taxonomy' => 'doc_category',
323 + 'field' => 'slug',
324 + 'terms' => $wp_query->query_vars['doc_category'],
325 + 'operator' => 'AND',
326 + 'include_children' => false
327 + ];
328 + } else if( isset( $wp_query->query_vars['name'] ) && isset( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] == 'docs' ) {
329 + $post = get_page_by_path($wp_query->query_vars['name'] , OBJECT, 'docs');
330 + $doc_terms = [];
350 331
351 - if ( is_user_logged_in() ) {
352 - $statuses[ ] = 'private';
353 - }
332 + if( isset( $post->ID ) ) {
333 + $terms = get_the_terms($post->ID, 'doc_category');
334 + if( ! empty( $terms ) ) {
335 + $doc_terms = wp_list_pluck( $terms, 'term_id' );
336 + }
337 + }
354 338
355 - $_args = array(
356 - 'post_status' => $statuses,
357 - // Required: with an explicit `post_status` WordPress only narrows private
358 - // docs to the ones the user may read when `perm` is `readable`. Without it,
359 - // listing `private` would expose every private doc to any logged-in user.
360 - 'perm' => 'readable',
361 - 'term_id' => $_terms[ 0 ]->term_id
362 - );
363 - if ( isset( $wp_query->query_vars[ 'doc_category' ] ) ) {
364 - $_args[ 'tax_query' ][ ] = array(
365 - 'taxonomy' => 'doc_category',
366 - 'field' => 'slug',
367 - 'terms' => $wp_query->query_vars[ 'doc_category' ],
368 - 'operator' => 'AND',
369 - 'include_children' => false
370 - );
371 - } elseif ( isset( $wp_query->query_vars[ 'name' ] ) && isset( $wp_query->query_vars[ 'post_type' ] ) && 'docs' == $wp_query->query_vars[ 'post_type' ] ) {
372 - $_post = get_page_by_path( $wp_query->query_vars[ 'name' ], OBJECT, 'docs' );
373 - $doc_terms = array();
339 + if( ! empty( $doc_terms ) ) {
340 + $_args['tax_query'][] = [
341 + 'taxonomy' => 'doc_category',
342 + 'field' => 'term_id',
343 + 'terms' => $doc_terms,
344 + 'operator' => 'AND',
345 + 'include_children' => false
346 + ];
347 + }
348 + }
374 349
375 - if ( isset( $_post->ID ) ) {
376 - $terms = get_the_terms( $_post->ID, 'doc_category' );
377 - if ( ! empty( $terms ) ) {
378 - $doc_terms = wp_list_pluck( $terms, 'term_id' );
379 - }
380 - }
350 + $_args['orderby'] = $_orderby;
351 + if ( $_orderby != 'betterdocs_order' ) {
352 + $_args['order'] = $_order;
353 + }
381 354
382 - if ( ! empty( $doc_terms ) ) {
383 - $_args[ 'tax_query' ][ ] = array(
384 - 'taxonomy' => 'doc_category',
385 - 'field' => 'term_id',
386 - 'terms' => $doc_terms,
387 - 'operator' => 'AND',
388 - 'include_children' => false
389 - );
390 - $_args[ 'term_id' ] = $doc_terms[ 0 ];
391 - }
392 - } else {
393 - // Fallback: use the term from current post
394 - $_args[ 'tax_query' ][ ] = array(
395 - 'taxonomy' => 'doc_category',
396 - 'field' => 'term_id',
397 - 'terms' => $_terms[ 0 ]->term_id,
398 - 'operator' => 'AND',
399 - 'include_children' => false
400 - );
401 - }
355 + /**
356 + * Before Query
357 + */
358 + do_action_ref_array( 'betterdocs_navigation_docs_query', [ &$_args ] );
359 + $docs = $this->get_posts( $this->docs_query_args( $_args ) );
402 360
403 - $_args[ 'orderby' ] = $_orderby;
404 - if ( 'betterdocs_order' != $_orderby ) {
405 - $_args[ 'order' ] = $_order;
406 - }
361 + $_docs = [];
362 + if ( $docs->have_posts() ) {
363 + array_map(
364 + function ( $post ) use ( &$_docs ) {
365 + $_docs[] = $post->ID;
366 + },
367 + $docs->posts
368 + );
369 + }
407 370
408 - /**
409 - * Before Query
410 - */
411 - do_action_ref_array( 'betterdocs_navigation_docs_query', array( &$_args ) );
412 - $docs = $this->get_posts( $this->docs_query_args( $_args ) );
371 + $_docs_order = $_docs;
372 + }
413 373
414 - $_docs = array();
415 - if ( $docs->have_posts() ) {
416 - array_map(
417 - function ( $_post ) use ( &$_docs ) {
418 - $_docs[ ] = $_post->ID;
419 - },
420 - $docs->posts
421 - );
422 - }
374 + $_docs_order = apply_filters( 'betterdocs_adjacent_docs_order', $_docs_order, $_terms );
423 375
424 - $_docs_order = $_docs;
425 - }
376 + $_id_index = array_search( $post->ID, $_docs_order );
377 + $_id_index = $adjacent === 'next' ? $_id_index + 1 : $_id_index - 1;
378 + $_id = isset( $_docs_order[ $_id_index ] ) ? (int) $_docs_order[ $_id_index ] : null;
426 379
427 - $_docs_order = apply_filters( 'betterdocs_adjacent_docs_order', $_docs_order, $_terms );
380 + return $wpdb->prepare( "WHERE p.ID = %s AND $_where", (int) $_id );
381 + }
428 382
429 - // Ensure consistent type comparison by converting all IDs to integers
430 - $_docs_order = array_map( 'intval', $_docs_order );
431 - $_docs_order = array_values( $_docs_order ); // Re-index array after type conversion
383 + public function parse_terms_args( $args = [] ) {
384 + $_default_args = [
385 + 'hide_empty' => true,
386 + 'taxonomy' => 'doc_category'
387 + ];
432 388
433 - $_id_index = array_search( (int) $post->ID, $_docs_order, true );
389 + // OrderBy & Order
390 + $_orderby = ! empty( $args['orderby'] ) && $args['orderby'] != 1 ? $args['orderby'] : 'name';
391 + $_order = ! empty( $args['order'] ) ? $args['order'] : '';
434 392
435 - // If current post not found in order list, return original where clause
436 - if ( false === $_id_index ) {
437 - return $where;
438 - }
393 + if ( $_orderby == 'betterdocs_order' ) {
394 + // Use base meta key - fallback logic will be handled in the terms_clauses filter
395 + $args['meta_key'] = 'doc_category_order';
396 + $args['orderby'] = 'meta_value_num';
397 + $args['order'] = 'ASC';
398 + } else {
399 + $args['orderby'] = $_orderby;
400 + $args['order'] = $_order;
401 + }
439 402
440 - $_id_index = 'next' === $adjacent ? $_id_index + 1 : $_id_index - 1;
441 - $_id = isset( $_docs_order[ $_id_index ] ) ? (int) $_docs_order[ $_id_index ] : null;
403 + // Nested Sub Category
404 + // $args['parent'] = 0;
405 + // if ( $nested_subcategory == true ) {
406 + // }
442 407
443 - // Fix: replace only ID comparison in where clause using regex
444 - if ( $_id ) {
445 - // This replaces any 'p.ID < N', 'p.ID > N', 'p.ID <= N', or 'p.ID >= N' etc, with 'p.ID = $_id'
446 - $where = preg_replace( '/p\.ID\s*[<>!=]+\s*\d+/', 'p.ID = ' . (int) $_id, $where );
447 - }
408 + if ( ! isset( $args['number'] ) ) {
409 + global $wp_query;
410 + if ( $wp_query->query === null || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
411 + $args['number'] = 4;
412 + }
413 + }
448 414
449 - return $where;
450 - }
415 + // Includes
416 + if ( isset( $args['include'] ) ) {
417 + $_include = ! is_array( $args['include'] ) ? explode( ',', $args['include'] ) : $args['include'];
418 + $args['include'] = $_include;
419 + $args['orderby'] = 'include';
451 420
452 - public function parse_terms_args( $args = array() ) {
453 - $_default_args = array(
454 - 'hide_empty' => true,
455 - 'taxonomy' => 'doc_category'
456 - );
421 + unset( $args['parent'] );
422 + }
457 423
458 - // OrderBy & Order
459 - $_orderby = ! empty( $args[ 'orderby' ] ) && 1 != $args[ 'orderby' ] ? $args[ 'orderby' ] : 'name';
460 - $_order = ! empty( $args[ 'order' ] ) ? $args[ 'order' ] : '';
424 + $_meta_query = ! empty( $args['meta_query'] ) ? $args['meta_query'] : [];
425 + $args['meta_query'] = apply_filters( 'betterdocs_taxonomy_object_meta_query', $_meta_query, $args );
461 426
462 - if ( 'betterdocs_order' == $_orderby ) {
463 - // Use base meta key - fallback logic will be handled in the terms_clauses filter
464 - $args[ 'meta_key' ] = 'doc_category_order';
465 - $args[ 'orderby' ] = 'meta_value_num';
466 - $args[ 'order' ] = 'ASC';
467 - } else {
468 - $args[ 'orderby' ] = $_orderby;
469 - $args[ 'order' ] = $_order;
470 - }
427 + return apply_filters( 'betterdocs_category_terms_object', wp_parse_args( $args, $_default_args ), $args );
428 + }
471 429
472 - // Nested Sub Category
473 - // $args['parent'] = 0;
474 - // if ( $nested_subcategory == true ) {
475 - // }
430 + public function get_terms( $args ) {
431 + $parsed_args = $this->parse_terms_args( $args );
432 + $terms = get_terms( $parsed_args );
476 433
477 - if ( ! isset( $args[ 'number' ] ) ) {
478 - global $wp_query;
479 - if ( null === $wp_query->query || ( isset( $wp_query->query[ 'post_type' ] ) && 'docs' != $wp_query->query[ 'post_type' ] ) ) {
480 - $args[ 'number' ] = 4;
481 - }
482 - }
434 + // Filter terms manually if we need to consider private docs for users with read_private_docs capability
435 + if ( isset( $parsed_args['_betterdocs_filter_private'] ) && $parsed_args['_betterdocs_filter_private'] && current_user_can( 'read_private_docs' ) ) {
436 + $terms = array_filter( $terms, function( $term ) {
437 + // Get the actual count including private docs for users with read_private_docs capability
438 + $actual_count = $this->get_docs_count( $term, false );
439 + return $actual_count > 0;
440 + });
441 + }
483 442
484 - // Includes
485 - if ( isset( $args[ 'include' ] ) ) {
486 - $_include = ! is_array( $args[ 'include' ] ) ? explode( ',', $args[ 'include' ] ) : $args[ 'include' ];
487 - $args[ 'include' ] = $_include;
488 - $args[ 'orderby' ] = 'include';
443 + return $terms;
444 + }
489 445
490 - unset( $args[ 'parent' ] );
491 - }
446 + public function get_child_terms( $args ) {
447 + if ( ! isset( $args['number'] ) ) {
448 + global $wp_query;
449 + if ( $wp_query->query === null || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
450 + $args['number'] = 1;
451 + }
452 + }
492 453
493 - $_meta_query = ! empty( $args[ 'meta_query' ] ) ? $args[ 'meta_query' ] : array();
494 - $args[ 'meta_query' ] = apply_filters( 'betterdocs_taxonomy_object_meta_query', $_meta_query, $args );
454 + return $this->get_terms( $args );
455 + }
495 456
496 - return apply_filters( 'betterdocs_category_terms_object', wp_parse_args( $args, $_default_args ), $args );
497 - }
457 + /**
458 + * Get POSTs of Docs type.
459 + *
460 + * @param mixed $args
461 + * @return WP_Query
462 + */
463 + public function get_posts( $args, $ignore = false ) {
464 + if ( ! $ignore ) {
465 + $args = $this->docs_query_args( $args );
466 + }
498 467
499 - public function get_terms( $args ) {
500 - $parsed_args = $this->parse_terms_args( $args );
501 - $terms = get_terms( $parsed_args );
468 + return new WP_Query( $args );
469 + }
502 470
503 - // Filter terms manually if we need to consider private docs the current user may read
504 - if ( isset( $parsed_args[ '_betterdocs_filter_private' ] ) && $parsed_args[ '_betterdocs_filter_private' ] && is_user_logged_in() ) {
505 - $terms = array_filter( $terms, function ( $term ) {
506 - // Get the actual count including private docs for users with read_private_docs capability
507 - return $this->get_private_inclusive_docs_count( $term ) > 0;
508 - } );
509 - }
471 + public function get_taxonomy( $tax = '' ) {
472 + global $wp_query;
473 + if ( is_tax( 'knowledge_base' ) ) {
474 + $_tax = $wp_query->tax_query->queried_terms;
475 + if ( array_key_exists( 'doc_category', $_tax ) ) {
476 + $tax = 'doc_category';
477 + } else {
478 + $tax = 'knowledge_base';
479 + }
480 + } elseif ( is_tax( 'doc_category' ) ) {
481 + $tax = 'doc_category';
482 + }
510 483
511 - return $terms;
512 - }
484 + return $tax;
485 + }
513 486
514 - /**
515 - * Drop terms with no visible docs after `hide_empty` was disabled for private docs.
516 - *
517 - * modify_terms_args_for_private_docs() turns `hide_empty` off so WordPress stops
518 - * dropping terms whose only docs are private. Without this counterpart, every
519 - * genuinely empty term would leak into the listing for privileged users. Runs only
520 - * for queries carrying the `_betterdocs_filter_private` flag, so anonymous and
521 - * unflagged queries are untouched.
522 - *
523 - * @param array|WP_Error $terms
524 - * @param array|null $taxonomies
525 - * @param array $args
526 - * @return array|WP_Error
527 - */
528 - public function filter_terms_for_private_docs( $terms, $taxonomies, $args ) {
529 - if ( empty( $args[ '_betterdocs_filter_private' ] ) || empty( $terms ) || is_wp_error( $terms ) ) {
530 - return $terms;
531 - }
487 + public function terms_query( $args = [] ) {
488 + global $wp_query;
489 + $_origin_args = $args;
532 490
533 - if ( ! is_user_logged_in() ) {
534 - return $terms;
535 - }
491 + $default_args = [
492 + 'hide_empty' => true,
493 + 'taxonomy' => 'doc_category',
494 + 'orderby' => 'name'
495 + ];
536 496
537 - // Only term objects can be counted; `ids`, `names`, `count`, ... pass through.
538 - $_fields = isset( $args[ 'fields' ] ) ? $args[ 'fields' ] : 'all';
539 - if ( ! in_array( $_fields, array( 'all', 'all_with_object_id' ), true ) ) {
540 - return $terms;
541 - }
497 + /**
498 + * Number Set
499 + *
500 + * @FIX: If Built-in Docs page off and docs_page in use, then Terms Query Number 4|1 set.
501 + */
502 + // if ( $wp_query->query === NULL || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
503 + // $default_args['number'] = 1;
504 + // }
542 505
543 - $_filtered = array_filter( $terms, function ( $term ) {
544 - if ( ! is_object( $term ) ) {
545 - return true;
546 - }
506 + /**
507 + * Nested Sub Category
508 + */
509 + if ( isset( $args['nested_subcategory'] ) && $args['nested_subcategory'] == true ) {
510 + $default_args['parent'] = 0;
511 + unset( $args['nested_subcategory'] );
512 + // if ( $wp_query->query === NULL || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
513 + // $default_args['number'] = 4;
514 + // }
515 + }
547 516
548 - return $this->get_private_inclusive_docs_count( $term ) > 0;
549 - } );
517 + /**
518 + * OrderBy and Order
519 + */
520 + if ( ! isset( $args['orderby'] ) ) {
521 + $_orderby = $this->settings->get( 'terms_orderby', 'name' );
522 + $_order = $this->settings->get( 'terms_order', '' );
523 + } else {
524 + $_orderby = $args['orderby'];
525 + $_order = ! empty( $args['order'] ) ? $args['order'] : '';
526 + }
550 527
551 - return array_values( $_filtered );
552 - }
528 + if ( 'betterdocs_order' === $_orderby ) {
529 + // Use different meta keys for different taxonomies
530 + if ( isset( $args['taxonomy'] ) && $args['taxonomy'] === 'knowledge_base' ) {
531 + $default_args['meta_key'] = 'kb_order';
532 + } else {
533 + $default_args['meta_key'] = 'doc_category_order';
534 + }
535 + $_orderby = 'meta_value_num';
536 + $_order = 'ASC';
537 + } elseif ( $_orderby === true ) {
538 + $_orderby = 'name';
539 + }
553 540
554 - /**
555 - * Docs count for a term, including private docs when the user may read them.
556 - *
557 - * KB terms need object-in-term counting rather than the doc_category count path,
558 - * which BetterDocs Pro provides through the filter below; get_docs_count() is the
559 - * fallback and already counts via get_objects_in_term() for the term's own taxonomy.
560 - *
561 - * @param WP_Term $term
562 - * @return int
563 - */
564 - /**
565 - * Whether the current user may see a doc in a listing.
566 - *
567 - * Public docs are visible to everyone. A private doc is visible to whoever may read
568 - * it — `read_post` maps to the base `read` capability for the doc's own author and
569 - * to `read_private_docs` for everyone else, so owners see their own private docs
570 - * without needing the capability. Other non-public statuses (draft, pending) stay
571 - * out of listings for everyone, as before.
572 - *
573 - * @param int $post_id
574 - * @return bool
575 - */
576 - /**
577 - * Cache-key fragment identifying whose visibility a cached count reflects.
578 - *
579 - * Everyone who can read every private doc sees the same numbers, so they share one
580 - * `priv` bucket; authors differ from each other and get their own. Logged-out
581 - * visitors all share bucket `0`, keeping the anonymous cache as hot as before.
582 - *
583 - * @return string
584 - */
585 - protected function count_cache_viewer_key() {
586 - if ( ! is_user_logged_in() ) {
587 - return '0';
588 - }
541 + $args['orderby'] = $_orderby;
542 + if ( ! empty( $_order ) ) {
543 + $args['order'] = $_order;
544 + }
589 545
590 - if ( current_user_can( 'read_private_docs' ) ) {
591 - return 'priv';
592 - }
546 + /**
547 + * @todo old hook
548 + * hook: betterdocs_child_taxonomy_meta_query
549 + */
550 + $_multiple_kb = apply_filters(
551 + 'betterdocs_query_args_multiple_kb_enabled',
552 + isset( $args['multiple_kb'] ) ? (bool) $args['multiple_kb'] : false,
553 + $_origin_args
554 + );
593 555
594 - return 'u' . get_current_user_id();
595 - }
556 + $_kb_slug = isset( $args['kb_slug'] ) ? trim( $args['kb_slug'] ) : '';
596 557
597 - public function can_read_doc( $post_id ) {
598 - if ( is_post_publicly_viewable( $post_id ) ) {
599 - return true;
600 - }
558 + unset( $args['multiple_kb'] );
559 + unset( $args['kb_slug'] );
601 560
602 - return 'private' === get_post_status( $post_id ) && current_user_can( 'read_post', $post_id );
603 - }
561 + $meta_query = ! empty( $args['meta_query'] ) ? $args['meta_query'] : [];
562 + $meta_query = apply_filters( 'betterdocs_terms_meta_query_args', $meta_query, $_multiple_kb, $_kb_slug, $_origin_args );
604 563
605 - protected function get_private_inclusive_docs_count( $term ) {
606 - /**
607 - * Let add-ons supply their own private-inclusive count for a term.
608 - *
609 - * Passing `null` means "not handled" — implementations that don't recognise the
610 - * term's taxonomy return the value untouched, and we fall back to get_docs_count().
611 - *
612 - * @param int|null $count
613 - * @param WP_Term $term
614 - */
615 - $_count = apply_filters( 'betterdocs_get_term_docs_count_for_private_filter', null, $term );
564 + if ( ! empty( $meta_query ) ) {
565 + $default_args['meta_query'] = $meta_query;
566 + }
616 567
617 - if ( null !== $_count ) {
618 - return (int) $_count;
619 - }
568 + if ( ! empty( $args['terms'] ) ) {
569 + $args['include'] = explode( ',', $args['terms'] );
570 + $args['orderby'] = 'include';
571 + $args['order'] = 'ASC';
620 572
621 - // Count nested sub-category docs too, so a parent whose docs live only in its
622 - // children stays visible to logged-in users exactly as it does for anonymous
623 - // visitors (whose grid is descendant-aware). get_docs_count( …, true ) already
624 - // filters each descendant doc through can_read_doc() via get_doc_ids_by_term(),
625 - // so private/unreadable docs never resurrect a term. A non-nested count here
626 - // hid those parents from logged-in users only.
627 - return (int) $this->get_docs_count( $term, true );
628 - }
573 + unset( $default_args['parent'] );
574 + unset( $args['parent'] );
575 + unset( $args['terms'] );
576 + }
629 577
630 - public function get_child_terms( $args ) {
631 - if ( ! isset( $args[ 'number' ] ) ) {
632 - global $wp_query;
633 - if ( null === $wp_query->query || ( isset( $wp_query->query[ 'post_type' ] ) && 'docs' != $wp_query->query[ 'post_type' ] ) ) {
634 - $args[ 'number' ] = 1;
635 - }
636 - }
578 + $_query_args = wp_parse_args( $args, $default_args );
579 + $_query_args = apply_filters( 'betterdocs_terms_query_args', $_query_args, $_origin_args );
637 580
638 - return $this->get_terms( $args );
639 - }
581 + // Apply private docs logic for logged-in users
582 + $_query_args = $this->modify_terms_args_for_private_docs( $_query_args );
640 583
641 - /**
642 - * Get POSTs of Docs type.
643 - *
644 - * @param mixed $args
645 - * @return WP_Query
646 - */
647 - public function get_posts( $args, $ignore = false ) {
648 - if ( ! $ignore ) {
649 - $args = $this->docs_query_args( $args );
650 - }
584 + return $_query_args;
585 + }
651 586
652 - return new WP_Query( $args );
653 - }
587 + public function get_term_parents( $term_id, $taxonomy = 'doc_category', $args = [] ) {
588 + $term = get_term( $term_id, $taxonomy );
589 + if ( is_wp_error( $term ) ) {
590 + return $term;
591 + }
654 592
655 - public function get_taxonomy( $tax = '' ) {
656 - global $wp_query;
657 - if ( is_tax( 'knowledge_base' ) ) {
658 - $_tax = $wp_query->tax_query->queried_terms;
659 - if ( array_key_exists( 'doc_category', $_tax ) ) {
660 - $tax = 'doc_category';
661 - } else {
662 - $tax = 'knowledge_base';
663 - }
664 - } elseif ( is_tax( 'doc_category' ) ) {
665 - $tax = 'doc_category';
666 - }
593 + if ( ! $term || ! isset( $term->term_id ) ) {
594 + return [];
595 + }
667 596
668 - return $tax;
669 - }
597 + $_lists = [];
598 + $origin_term = $term_id;
599 + $term_id = $term->term_id;
670 600
671 - public function terms_query( $args = array() ) {
672 - global $wp_query;
673 - $_origin_args = $args;
601 + $defaults = [
602 + 'format' => 'name',
603 + 'inclusive' => true
604 + ];
674 605
675 - $default_args = array(
676 - 'hide_empty' => true,
677 - 'taxonomy' => 'doc_category',
678 - 'orderby' => 'name'
679 - );
606 + $args = wp_parse_args( $args, $defaults );
680 607
681 - /**
682 - * Number Set
683 - *
684 - * @FIX: If Built-in Docs page off and docs_page in use, then Terms Query Number 4|1 set.
685 - */
686 - // if ( $wp_query->query === NULL || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
687 - // $default_args['number'] = 1;
688 - // }
608 + $args['inclusive'] = wp_validate_boolean( $args['inclusive'] );
689 609
690 - /**
691 - * Nested Sub Category
692 - */
693 - if ( isset( $args[ 'nested_subcategory' ] ) && true == $args[ 'nested_subcategory' ] ) {
694 - $default_args[ 'parent' ] = 0;
695 - unset( $args[ 'nested_subcategory' ] );
696 - // if ( $wp_query->query === NULL || ( isset( $wp_query->query['post_type'] ) && $wp_query->query['post_type'] != 'docs' ) ) {
697 - // $default_args['number'] = 4;
698 - // }
699 - }
610 + $parents = get_ancestors( $term_id, $taxonomy );
700 611
701 - /**
702 - * OrderBy and Order
703 - */
704 - if ( ! isset( $args[ 'orderby' ] ) ) {
705 - $_orderby = $this->settings->get( 'terms_orderby', 'name' );
706 - $_order = $this->settings->get( 'terms_order', '' );
707 - } else {
708 - $_orderby = $args[ 'orderby' ];
709 - $_order = ! empty( $args[ 'order' ] ) ? $args[ 'order' ] : '';
710 - }
612 + if ( $args['inclusive'] ) {
613 + array_unshift( $parents, $term_id );
614 + }
711 615
712 - if ( 'betterdocs_order' === $_orderby ) {
713 - // Use different meta keys for different taxonomies
714 - if ( isset( $args[ 'taxonomy' ] ) && 'knowledge_base' === $args[ 'taxonomy' ] ) {
715 - $default_args[ 'meta_key' ] = 'kb_order';
716 - } else {
717 - $default_args[ 'meta_key' ] = 'doc_category_order';
718 - }
719 - $_orderby = 'meta_value_num';
720 - $_order = 'ASC';
721 - } elseif ( true === $_orderby ) {
722 - $_orderby = 'name';
723 - }
616 + foreach ( array_reverse( $parents ) as $term_id ) {
617 + $parent = get_term( $term_id, $taxonomy );
618 + $name = ( 'slug' === $args['format'] ) ? $parent->slug : $parent->name;
619 + $term_permalink = get_term_link( $parent->term_id, $taxonomy );
620 + $term_permalink = apply_filters( 'betterdocs_breadcrumb_term_permalink', $term_permalink, $term_id );
724 621
725 - $args[ 'orderby' ] = $_orderby;
726 - if ( ! empty( $_order ) ) {
727 - $args[ 'order' ] = $_order;
728 - }
622 + $_item = [
623 + 'url' => $term_permalink,
624 + 'text' => $name
625 + ];
729 626
730 - /**
731 - * @todo old hook
732 - * hook: betterdocs_child_taxonomy_meta_query
733 - */
734 - $_multiple_kb = apply_filters(
735 - 'betterdocs_query_args_multiple_kb_enabled',
736 - isset( $args[ 'multiple_kb' ] ) ? (bool) $args[ 'multiple_kb' ] : false,
737 - $_origin_args
738 - );
627 + $_lists[] = $_item;
628 + }
739 629
740 - $_kb_slug = isset( $args[ 'kb_slug' ] ) ? trim( $args[ 'kb_slug' ] ) : '';
630 + return apply_filters( 'betterdocs_breadcrumb_archive_lists', $_lists, $origin_term );
631 + }
741 632
742 - unset( $args[ 'multiple_kb' ] );
743 - unset( $args[ 'kb_slug' ] );
633 + /**
634 + * Get all non-empty child term IDs recursively for a given taxonomy and parent term.
635 + *
636 + * This function retrieves all child terms for a specified taxonomy and parent term,
637 + * recursively fetching child terms of child terms, and returns only those with a non-zero post count.
638 + *
639 + * @param string $taxonomy The taxonomy name (e.g., 'doc_category').
640 + * @param int $parent_id The ID of the parent term to start retrieving children from.
641 + *
642 + * @return array An array of non-empty child term IDs.
643 + */
644 + public function get_all_child_term_ids( $taxonomy, $parent_id ) {
645 + // Set up the arguments for retrieving child terms
646 + $args = apply_filters(
647 + 'betterdocs_get_child_term_ids_args',
648 + [
649 + 'taxonomy' => $taxonomy,
650 + 'parent' => $parent_id,
651 + 'hide_empty' => true,
652 + 'fields' => 'ids'
653 + ]
654 + );
744 655
745 - $meta_query = ! empty( $args[ 'meta_query' ] ) ? $args[ 'meta_query' ] : array();
746 - $meta_query = apply_filters( 'betterdocs_terms_meta_query_args', $meta_query, $_multiple_kb, $_kb_slug, $_origin_args );
656 + // Get the terms based on the arguments
657 + $terms = get_terms( $args );
747 658
748 - if ( ! empty( $meta_query ) ) {
749 - $default_args[ 'meta_query' ] = $meta_query;
750 - }
659 + // Initialize an empty array to hold non-empty child term IDs
660 + $non_empty_children = [];
751 661
752 - if ( ! empty( $args[ 'terms' ] ) ) {
753 - $args[ 'include' ] = explode( ',', $args[ 'terms' ] );
754 - $args[ 'orderby' ] = 'include';
755 - $args[ 'order' ] = 'ASC';
662 + // Check if terms were retrieved without errors and that the result isn't empty
663 + if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
664 + $term_ids = [];
756 665
757 - unset( $default_args[ 'parent' ] );
758 - unset( $args[ 'parent' ] );
759 - unset( $args[ 'terms' ] );
760 - }
666 + // Loop through each term ID
667 + foreach ( $terms as $term_id ) {
668 + // Add the current term ID to the term_ids array
669 + $term_ids[] = $term_id;
761 670
762 - $_query_args = wp_parse_args( $args, $default_args );
763 - $_query_args = apply_filters( 'betterdocs_terms_query_args', $_query_args, $_origin_args );
671 + // Recursively get child terms for the current term
672 + $child_term_ids = $this->get_all_child_term_ids( $taxonomy, $term_id );
764 673
765 - // Apply private docs logic for logged-in users
766 - $_query_args = $this->modify_terms_args_for_private_docs( $_query_args );
674 + // If there are child terms, merge them into the term_ids array
675 + if ( ! empty( $child_term_ids ) ) {
676 + $term_ids = array_merge( $term_ids, $child_term_ids );
677 + }
678 + }
767 679
768 - return $_query_args;
769 - }
680 + // Loop through all retrieved term IDs to filter out empty ones
681 + foreach ( $term_ids as $term_id ) {
682 + // Get the term object for the current term ID
683 + $child_term = get_term( $term_id, $taxonomy );
770 684
771 - public function get_term_parents( $term_id, $taxonomy = 'doc_category', $args = array() ) {
772 - $term = get_term( $term_id, $taxonomy );
773 - if ( is_wp_error( $term ) ) {
774 - return $term;
775 - }
685 + // Only include terms that have a non-zero post count
686 + if ( $child_term && isset( $child_term->term_id ) && $child_term->count > 0 ) {
687 + $non_empty_children[] = $child_term->term_id;
688 + }
689 + }
690 + }
776 691
777 - if ( ! $term || ! isset( $term->term_id ) ) {
778 - return array();
779 - }
692 + // Return the final array of non-empty child term IDs
693 + return $non_empty_children;
694 + }
780 695
781 - $_lists = array();
782 - $origin_term = $term_id;
783 - $term_id = $term->term_id;
696 + /**
697 + * Get all nested child term IDs of a specific parent term in a taxonomy and return as a comma-separated string.
698 + *
699 + * @param string $taxonomy The taxonomy.
700 + * @param int $parent_id The parent term ID.
701 + * @return string The comma-separated term IDs.
702 + */
703 + public function get_child_term_ids_by_parent_id( $taxonomy, $parent_id ) {
704 + $term_ids = $this->get_all_child_term_ids( $taxonomy, $parent_id );
705 + return implode( ',', $term_ids );
706 + }
784 707
785 - $defaults = array(
786 - 'format' => 'name',
787 - 'inclusive' => true
788 - );
708 + public function get_terms_children( $taxonomy, $parent_id ) {
709 + $children = get_term_children( $parent_id, $taxonomy );
710 + $non_empty_children = [];
711 + if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
712 + foreach ( $children as $child_id ) {
713 + $child_term = get_term( $child_id, $taxonomy );
789 714
790 - $args = wp_parse_args( $args, $defaults );
715 + // Only include non-empty terms
716 + if ( $child_term && $child_term->count > 0 ) {
717 + $non_empty_children[] = $child_term;
718 + }
719 + }
720 + }
791 721
792 - $args[ 'inclusive' ] = wp_validate_boolean( $args[ 'inclusive' ] );
722 + return $non_empty_children;
723 + }
793 724
794 - $parents = get_ancestors( $term_id, $taxonomy );
725 + public function get_terms_children_ids( $taxonomy, $parent_id ) {
726 + $children = $this->get_terms_children( $taxonomy, $parent_id );
727 + $term_ids = wp_list_pluck( $children, 'term_id' );
795 728
796 - if ( $args[ 'inclusive' ] ) {
797 - array_unshift( $parents, $term_id );
798 - }
729 + return implode( ',', $term_ids );
730 + }
799 731
800 - foreach ( array_reverse( $parents ) as $term_id ) {
801 - $parent = get_term( $term_id, $taxonomy );
802 - $name = ( 'slug' === $args[ 'format' ] ) ? $parent->slug : $parent->name;
803 - $term_permalink = get_term_link( $parent->term_id, $taxonomy );
804 - $term_permalink = apply_filters( 'betterdocs_breadcrumb_term_permalink', $term_permalink, $term_id );
732 + public function count_terms_children( $taxonomy, $parent_id ) {
733 + return count( $this->get_terms_children( $taxonomy, $parent_id ) );
734 + }
805 735
806 - $_item = array(
807 - 'url' => $term_permalink,
808 - 'text' => $name
809 - );
736 + public function is_inner_templates() {
737 + if ( is_tax( 'knowledge_base' ) || is_tax( 'doc_category' ) || is_tax( 'doc_tag' ) || is_singular( 'docs' ) ) {
738 + return true;
739 + }
740 + return false;
741 + }
810 742
811 - $_lists[ ] = $_item;
812 - }
743 + /**
744 + * Summary of docs_query_args
745 + * @param mixed $args
746 + * @throws \Exception
747 + * @return mixed
748 + */
749 + public function docs_query_args( $args, $filter = [] ) {
750 + $_origin_args = $args;
813 751
814 - return apply_filters( 'betterdocs_breadcrumb_archive_lists', $_lists, $origin_term );
815 - }
752 + $default_args = [
753 + 'post_type' => 'docs'
754 + ];
816 755
817 - /**
818 - * Get all non-empty child term IDs recursively for a given taxonomy and parent term.
819 - *
820 - * This function retrieves all child terms for a specified taxonomy and parent term,
821 - * recursively fetching child terms of child terms, and returns only those with a non-zero post count.
822 - *
823 - * @param string $taxonomy The taxonomy name (e.g., 'doc_category').
824 - * @param int $parent_id The ID of the parent term to start retrieving children from.
825 - *
826 - * @return array An array of non-empty child term IDs.
827 - */
828 - public function get_all_child_term_ids( $taxonomy, $parent_id ) {
829 - $version = $this->database->get_cache_version( 'betterdocs_term_counts' );
830 - $cache_key = "bd_term_counts_v{$version}_child_ids_{$taxonomy}_{$parent_id}";
756 + if ( ! empty( $args['post_type'] ) && trim( $args['post_type'] ) === 'docs_any' ) {
757 + $default_args['post_type'] = 'docs';
758 + $default_args['post_status'] = 'any';
831 759
832 - $cached = wp_cache_get( $cache_key, 'betterdocs' );
833 - if ( false !== $cached ) {
834 - return $cached;
835 - }
760 + unset( $args['post_type'] );
761 + }
836 762
837 - // get_terms( child_of => X ) walks the full descendant tree using WP's
838 - // internally cached term hierarchy, replacing the previous recursive
839 - // get_term()-in-a-loop pattern with one call.
840 - $args = apply_filters(
841 - 'betterdocs_get_child_term_ids_args',
842 - array(
843 - 'taxonomy' => $taxonomy,
844 - 'child_of' => $parent_id,
845 - 'hide_empty' => true,
846 - 'fields' => 'ids',
847 - )
848 - );
763 + /**
764 + * OrderBy and Order
765 + */
766 + if ( ! isset( $args['orderby'] ) ) {
767 + $_orderby = $this->settings->get( 'alphabetically_order_post' );
768 + $_order = $this->settings->get( 'docs_order', 'ASC' );
769 + } else {
770 + $_orderby = $args['orderby'];
771 + $_order = ! empty( $args['order'] ) ? $args['order'] : 'ASC';
772 + }
849 773
850 - $ids = get_terms( $args );
851 - $ids = ( is_wp_error( $ids ) || ! is_array( $ids ) ) ? array() : array_map( 'intval', $ids );
774 + if ( 'betterdocs_order' != $_orderby ) {
775 + if ( $_orderby === true ) {
776 + $args['orderby'] = 'title';
777 + } else {
778 + $args['orderby'] = $_orderby;
779 + }
852 780
853 - wp_cache_set( $cache_key, $ids, 'betterdocs', HOUR_IN_SECONDS * 6 );
781 + $args['order'] = $_order;
782 + } elseif ( 'betterdocs_order' == $_orderby ) {
783 + unset( $args['orderby'] );
784 + }
854 785
855 - return $ids;
856 - }
786 + if ( empty( $args['orderby'] ) ) {
787 + unset( $args['order'] );
788 + }
857 789
858 - /**
859 - * Get all nested child term IDs of a specific parent term in a taxonomy and return as a comma-separated string.
860 - *
861 - * @param string $taxonomy The taxonomy.
862 - * @param int $parent_id The parent term ID.
863 - * @return string The comma-separated term IDs.
864 - */
865 - public function get_child_term_ids_by_parent_id( $taxonomy, $parent_id ) {
866 - $term_ids = $this->get_all_child_term_ids( $taxonomy, $parent_id );
867 - return implode( ',', $term_ids );
868 - }
790 + /**
791 + * Term ID
792 + */
793 + $_term_id = null;
794 + if ( ! empty( $args['term_id'] ) ) {
795 + $_term_id = intval( $args['term_id'] );
796 + unset( $args['term_id'] );
797 + }
869 798
870 - public function get_terms_children( $taxonomy, $parent_id ) {
871 - $children = get_term_children( $parent_id, $taxonomy );
872 - $non_empty_children = array();
873 - if ( ! is_wp_error( $children ) && ! empty( $children ) ) {
874 - foreach ( $children as $child_id ) {
875 - $child_term = get_term( $child_id, $taxonomy );
799 + // if ( $_term_id == null ) {
800 + // throw new \Exception( __( '$args["term_id"] cannot be null.', 'betterdocs' ) );
801 + // }
876 802
877 - // Only include non-empty terms
878 - if ( $child_term && $child_term->count > 0 ) {
879 - $non_empty_children[ ] = $child_term;
880 - }
881 - }
882 - }
803 + /**
804 + * Term Slug for tax_query
805 + */
806 + $_term_slug = '';
807 + if ( ! empty( $args['term_slug'] ) ) {
808 + $_term_slug = trim( $args['term_slug'] );
809 + unset( $args['term_slug'] );
810 + }
883 811
884 - return $non_empty_children;
885 - }
812 + /**
813 + * @todo old hook
814 + * hook: betterdocs_cat_template_multikb
815 + */
886 816
887 - public function get_terms_children_ids( $taxonomy, $parent_id ) {
888 - $children = $this->get_terms_children( $taxonomy, $parent_id );
889 - $term_ids = wp_list_pluck( $children, 'term_id' );
817 + $_multiple_kb = apply_filters(
818 + 'betterdocs_enable_multiple_knowledge_base',
819 + isset( $args['multiple_kb'] ) ? (bool) $args['multiple_kb'] : false,
820 + $_origin_args
821 + );
890 822
891 - return implode( ',', $term_ids );
892 - }
823 + $_kb_slug = isset( $args['kb_slug'] ) ? trim( $args['kb_slug'] ) : '';
893 824
894 - public function count_terms_children( $taxonomy, $parent_id ) {
895 - return count( $this->get_terms_children( $taxonomy, $parent_id ) );
896 - }
825 + unset( $args['multiple_kb'] );
826 + unset( $args['kb_slug'] );
897 827
898 - public function is_inner_templates() {
899 - if ( is_tax( 'knowledge_base' ) || is_tax( 'doc_category' ) || is_tax( 'doc_tag' ) || is_singular( 'docs' ) ) {
900 - return true;
901 - }
902 - return false;
903 - }
828 + $tax_query = [
829 + [
830 + 'taxonomy' => 'doc_category',
831 + 'field' => 'slug',
832 + 'terms' => $_term_slug,
833 + 'operator' => 'AND',
834 + 'include_children' => false
835 + ]
836 + ];
904 837
905 - /**
906 - * Summary of docs_query_args
907 - * @param mixed $args
908 - * @throws \Exception
909 - * @return mixed
910 - */
911 - public function docs_query_args( $args, $filter = array() ) {
912 - $_origin_args = $args;
838 + if ( ! isset( $args['orderby'] ) || $args['orderby'] == 'betterdocs_order' ) {
839 + $args['orderby'] = 'post__in';
840 + $args['post__in'] = $this->get_docs_order_by_terms( $_term_id );
841 + }
913 842
914 - $default_args = array(
915 - 'post_type' => 'docs'
916 - );
843 + if ( isset( $args['tax_query'] ) ) {
844 + $tax_query = $args['tax_query'];
845 + }
917 846
918 - if ( ! empty( $args[ 'post_type' ] ) && trim( $args[ 'post_type' ] ) === 'docs_any' ) {
919 - $default_args[ 'post_type' ] = 'docs';
920 - $default_args[ 'post_status' ] = 'any';
847 + $args['tax_query'] = apply_filters(
848 + 'betterdocs_docs_tax_query_args',
849 + $tax_query,
850 + $_multiple_kb,
851 + $_term_slug,
852 + $_kb_slug,
853 + $_origin_args,
854 + $this->is_inner_templates()
855 + );
856 + /**
857 + * Final parse args
858 + */
859 + $args = wp_parse_args( $args, $default_args );
921 860
922 - unset( $args[ 'post_type' ] );
923 - }
861 + if ( ! empty( $filter ) ) {
862 + $filter = array_flip( $filter );
863 + $args = array_filter(
864 + $args,
865 + function ( $item ) use ( $filter ) {
866 + return ! array_key_exists( $item, $filter );
867 + },
868 + ARRAY_FILTER_USE_KEY
869 + );
870 + }
924 871
925 - /**
926 - * OrderBy and Order
927 - */
928 - if ( ! isset( $args[ 'orderby' ] ) ) {
929 - $_orderby = $this->settings->get( 'alphabetically_order_post' );
930 - $_order = $this->settings->get( 'docs_order', 'ASC' );
931 - } else {
932 - $_orderby = $args[ 'orderby' ];
933 - $_order = ! empty( $args[ 'order' ] ) ? $args[ 'order' ] : 'ASC';
934 - }
872 + $final_args = apply_filters( 'betterdocs_articles_args', $args, $_term_id, $_origin_args );
935 873
936 - if ( 'betterdocs_order' != $_orderby ) {
937 - if ( true === $_orderby ) {
938 - $args[ 'orderby' ] = 'title';
939 - } else {
940 - $args[ 'orderby' ] = $_orderby;
941 - }
874 + // Process betterdocs_order AFTER all filters have run
875 + if ( isset( $final_args['orderby'] ) && $final_args['orderby'] == 'betterdocs_order' ) {
876 + $docs_order = $this->get_docs_order_by_terms( $_term_id );
942 877
943 - $args[ 'order' ] = $_order;
944 - } elseif ( 'betterdocs_order' == $_orderby ) {
945 - unset( $args[ 'orderby' ] );
946 - }
878 + if ( ! empty( $docs_order ) ) {
879 + $final_args['orderby'] = 'post__in';
880 + $final_args['post__in'] = $docs_order;
881 + } else {
882 + $final_args['orderby'] = 'menu_order';
883 + $final_args['order'] = 'ASC';
884 + }
885 + }
947 886
948 - if ( empty( $args[ 'orderby' ] ) ) {
949 - unset( $args[ 'order' ] );
950 - }
887 + return $final_args;
888 + }
951 889
952 - /**
953 - * Term ID
954 - */
955 - $_term_id = null;
956 - if ( ! empty( $args[ 'term_id' ] ) ) {
957 - $_term_id = intval( $args[ 'term_id' ] );
958 - unset( $args[ 'term_id' ] );
959 - }
890 + public function faq_terms_query_args( $includes = '', $excludes = '', $args = [] ) {
891 + $_args = [
892 + 'taxonomy' => 'betterdocs_faq_category',
893 + 'meta_key' => 'order',
894 + 'orderby' => 'meta_value_num',
895 + 'order' => 'ASC',
896 + 'include' => $includes,
897 + 'exclude' => $excludes,
898 + 'meta_query' => [
899 + [
900 + 'key' => 'status',
901 + 'value' => 1,
902 + 'compare' => '=='
903 + ]
904 + ]
905 + ];
960 906
961 - // if ( $_term_id == null ) {
962 - // throw new \Exception( __( '$args["term_id"] cannot be null.', 'betterdocs' ) );
963 - // }
907 + if ( $_args['include'] == 'all' ) {
908 + unset( $_args['include'] );
909 + unset( $_args['exclude'] );
910 + }
964 911
965 - /**
966 - * Term Slug for tax_query
967 - */
968 - $_term_slug = '';
969 - if ( ! empty( $args[ 'term_slug' ] ) ) {
970 - $_term_slug = trim( $args[ 'term_slug' ] );
971 - unset( $args[ 'term_slug' ] );
972 - }
912 + if ( empty( $_args['exclude'] ) ) {
913 + unset( $_args['exclude'] );
914 + }
973 915
974 - /**
975 - * @todo old hook
976 - * hook: betterdocs_cat_template_multikb
977 - */
916 + if ( empty( $_args['include'] ) ) {
917 + unset( $_args['include'] );
918 + }
978 919
979 - $_multiple_kb = apply_filters(
980 - 'betterdocs_enable_multiple_knowledge_base',
981 - isset( $args[ 'multiple_kb' ] ) ? (bool) $args[ 'multiple_kb' ] : false,
982 - $_origin_args
983 - );
920 + return wp_parse_args( $args, $_args );
921 + }
984 922
985 - $_kb_slug = isset( $args[ 'kb_slug' ] ) ? trim( $args[ 'kb_slug' ] ) : '';
923 + public function get_faq_by_term( $term_id ) {
924 + global $wpdb;
986 925
987 - unset( $args[ 'multiple_kb' ] );
988 - unset( $args[ 'kb_slug' ] );
926 + $args = [
927 + 'post_type' => 'betterdocs_faq',
928 + 'post_status' => 'publish',
929 + 'tax_query' => [
930 + [
931 + 'taxonomy' => 'betterdocs_faq_category',
932 + 'field' => 'term_id',
933 + 'terms' => $term_id,
934 + 'operator' => 'AND'
935 + ]
936 + ],
937 + 'posts_per_page' => -1
938 + ];
989 939
990 - $tax_query = array(
991 - array(
992 - 'taxonomy' => 'doc_category',
993 - 'field' => 'slug',
994 - 'terms' => $_term_slug,
995 - 'operator' => 'AND',
996 - 'include_children' => false
997 - )
998 - );
940 + $args['orderby'] = 'post__in';
941 + $args['post__in'] = $this->get_faq_orders( $term_id );
999 942
1000 - if ( ! isset( $args[ 'orderby' ] ) || 'betterdocs_order' == $args[ 'orderby' ] ) {
1001 - $args[ 'orderby' ] = 'post__in';
1002 - $args[ 'post__in' ] = $this->get_docs_order_by_terms( $_term_id );
1003 - }
943 + return new WP_Query( $args );
944 + }
1004 945
1005 - if ( isset( $args[ 'tax_query' ] ) ) {
1006 - $tax_query = $args[ 'tax_query' ];
1007 - }
946 + public function get_faq_orders( $term_id = null ) {
947 + global $wpdb;
948 + $faq_order = get_term_meta( $term_id, '_betterdocs_faq_order', true );
949 + $faq_order = explode( ',', $faq_order );
1008 950
1009 - $args[ 'tax_query' ] = apply_filters(
1010 - 'betterdocs_docs_tax_query_args',
1011 - $tax_query,
1012 - $_multiple_kb,
1013 - $_term_slug,
1014 - $_kb_slug,
1015 - $_origin_args,
1016 - $this->is_inner_templates()
1017 - );
1018 - /**
1019 - * Final parse args
1020 - */
1021 - $args = wp_parse_args( $args, $default_args );
951 + $query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}term_relationships WHERE term_taxonomy_id = %d", $term_id );
952 + $query_key = 'betterdocs_faq_order_' . md5( $query );
1022 953
1023 - if ( ! empty( $filter ) ) {
1024 - $filter = array_flip( $filter );
1025 - $args = array_filter(
1026 - $args,
1027 - function ( $item ) use ( $filter ) {
1028 - return ! array_key_exists( $item, $filter );
1029 - },
1030 - ARRAY_FILTER_USE_KEY
1031 - );
1032 - }
954 + if ( ( $results = $this->database->get_cache( $query_key ) ) !== false ) {
955 + return $results;
956 + }
1033 957
1034 - $final_args = apply_filters( 'betterdocs_articles_args', $args, $_term_id, $_origin_args );
958 + if ( ! empty( $faq_order ) ) {
959 + $new_ids = [];
960 + $results = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1035 961
1036 - // Process betterdocs_order AFTER all filters have run
1037 - if ( isset( $final_args[ 'orderby' ] ) && 'betterdocs_order' == $final_args[ 'orderby' ] ) {
1038 - $docs_order = $this->get_docs_order_by_terms( $_term_id );
962 + if ( ! is_null( $results ) && ! empty( $results ) && is_array( $results ) ) {
963 + $object_ids = array_filter(
964 + $results,
965 + function ( $value ) use ( $faq_order ) {
966 + return ! in_array( $value->object_id, $faq_order );
967 + }
968 + );
1039 969
1040 - if ( ! empty( $docs_order ) ) {
1041 - $final_args[ 'orderby' ] = 'post__in';
1042 - $final_args[ 'post__in' ] = $docs_order;
1043 - } else {
1044 - $final_args[ 'orderby' ] = 'menu_order';
1045 - $final_args[ 'order' ] = 'ASC';
1046 - }
1047 - }
970 + if ( ! empty( $object_ids ) ) {
971 + array_walk(
972 + $object_ids,
973 + function ( $value ) use ( &$new_ids ) {
974 + $new_ids[] = $value->object_id;
975 + }
976 + );
977 + }
978 + }
1048 979
1049 - return $final_args;
1050 - }
980 + $faq_order = array_merge( $new_ids, $faq_order );
981 + }
1051 982
1052 - /**
1053 - * The front-end FAQ ordering preference, set via the FAQ Builder header
1054 - * dropdown (the `.betterdocs-dropdown-select` control, saved to the
1055 - * `betterdocs_faq_order` option). The front end mirrors the builder so it
1056 - * shows FAQ groups (and the FAQs inside them) in the same order the admin
1057 - * sees while building.
1058 - *
1059 - * @return string One of: default, most_recent, least_recent, a_to_z, z_to_a, most_questions.
1060 - */
1061 - public function get_faq_order_key() {
1062 - $key = get_option( 'betterdocs_faq_order', 'default' );
1063 - $allowed = array( 'default', 'most_recent', 'least_recent', 'a_to_z', 'z_to_a', 'most_questions' );
983 + $this->database->set_cache( $query_key, $faq_order, 1 );
1064 984
1065 - if ( ! in_array( $key, $allowed, true ) ) {
1066 - $key = 'default';
1067 - }
985 + return $faq_order;
986 + }
1068 987
1069 - return apply_filters( 'betterdocs_faq_order_key', $key );
1070 - }
988 + public function get_faq_terms( $terms = [] ) {
989 + $_terms = get_terms(
990 + [
991 + 'taxonomy' => 'betterdocs_faq_category',
992 + 'hide_empty' => true,
993 + 'orderby' => 'name',
994 + 'order' => 'ASC',
995 + 'meta_query' => [
996 + [
997 + 'key' => 'status',
998 + 'value' => 1,
999 + 'compare' => '=='
1000 + ]
1001 + ]
1002 + ]
1003 + );
1071 1004
1072 - /**
1073 - * Translate the FAQ order preference into `get_terms()` order clauses for
1074 - * the FAQ group list. Mirrors the admin builder's ORDER_MAP so the front
1075 - * end matches what's configured there.
1076 - *
1077 - * @return array orderby/order (+ meta_key for the manual `default` order).
1078 - */
1079 - public function faq_terms_order_clause() {
1080 - switch ( $this->get_faq_order_key() ) {
1081 - case 'most_recent':
1082 - return array( 'orderby' => 'term_id', 'order' => 'DESC' );
1083 - case 'least_recent':
1084 - return array( 'orderby' => 'term_id', 'order' => 'ASC' );
1085 - case 'a_to_z':
1086 - return array( 'orderby' => 'name', 'order' => 'ASC' );
1087 - case 'z_to_a':
1088 - return array( 'orderby' => 'name', 'order' => 'DESC' );
1089 - case 'most_questions':
1090 - return array( 'orderby' => 'count', 'order' => 'DESC' );
1091 - case 'default':
1092 - default:
1093 - // Manual drag-drop order stored in the `order` term meta.
1094 - return array( 'meta_key' => 'order', 'orderby' => 'meta_value_num', 'order' => 'ASC' );
1095 - }
1096 - }
1005 + if ( ! is_wp_error( $_terms ) ) {
1006 + foreach ( $_terms as $term ) {
1007 + $terms[ $term->term_id ] = $term->name;
1008 + }
1009 + }
1097 1010
1098 - public function faq_terms_query_args( $includes = '', $excludes = '', $args = array(), $taxonomy = 'betterdocs_faq_category' ) {
1099 - $_args = array(
1100 - 'taxonomy' => $taxonomy,
1101 - 'include' => $includes,
1102 - 'exclude' => $excludes,
1103 - 'meta_query' => array(
1104 - array(
1105 - 'key' => 'status',
1106 - 'value' => 1,
1107 - 'compare' => '=='
1108 - )
1109 - )
1110 - );
1011 + return $terms;
1012 + }
1111 1013
1112 - $_args = array_merge( $_args, $this->faq_terms_order_clause() );
1014 + public function get_doc_terms( $terms = [] ) {
1015 + $_terms = get_terms(
1016 + [
1017 + 'taxonomy' => 'doc_category',
1018 + 'hide_empty' => true,
1019 + 'orderby' => 'name',
1020 + 'order' => 'ASC',
1021 + ]
1022 + );
1113 1023
1114 - if ( 'all' == $_args[ 'include' ] ) {
1115 - unset( $_args[ 'include' ] );
1116 - unset( $_args[ 'exclude' ] );
1117 - }
1024 + if ( ! is_wp_error( $_terms ) ) {
1025 + foreach ( $_terms as $term ) {
1026 + $terms[ $term->term_id ] = $term->name;
1027 + }
1028 + }
1118 1029
1119 - if ( empty( $_args[ 'exclude' ] ) ) {
1120 - unset( $_args[ 'exclude' ] );
1121 - }
1030 + return $terms;
1031 + }
1122 1032
1123 - if ( empty( $_args[ 'include' ] ) ) {
1124 - unset( $_args[ 'include' ] );
1125 - }
1126 1033
1127 - return wp_parse_args( $args, $_args );
1128 - }
1034 + public function get_docs_count( $term, $nested_subcategory = false, $args = [] ) {
1035 + // Validate term object
1036 + if ( ! is_object( $term ) ) {
1037 + return 0;
1038 + }
1129 1039
1130 - public function get_faq_by_term( $term_id, $taxonomy = 'betterdocs_faq_category' ) {
1131 - global $wpdb;
1040 + $counts = isset( $term->count ) ? $term->count : 0;
1132 1041
1133 - $args = array(
1134 - 'post_type' => 'betterdocs_faq',
1135 - 'post_status' => 'publish',
1136 - 'tax_query' => array(
1137 - array(
1138 - 'taxonomy' => $taxonomy,
1139 - 'field' => 'term_id',
1140 - 'terms' => $term_id,
1141 - 'operator' => 'AND'
1142 - )
1143 - ),
1144 - 'posts_per_page' => -1
1145 - );
1042 + if ( $nested_subcategory == false ) {
1043 + // For non-nested categories, we need to recalculate counts based on user capabilities
1044 + // Only proceed if we have a valid term with required properties
1045 + if ( isset( $term->term_id ) && isset( $term->taxonomy ) && is_numeric( $term->term_id ) ) {
1046 + // Get all post IDs for this term
1047 + $post_ids = get_objects_in_term( $term->term_id, $term->taxonomy );
1146 1048
1147 - // Order the FAQs inside the group to mirror the FAQ Builder header
1148 - // dropdown. `default`/`most_questions` keep the manual drag-drop order
1149 - // (the others sort live, just like the admin builder does).
1150 - switch ( $this->get_faq_order_key() ) {
1151 - case 'most_recent':
1152 - $args[ 'orderby' ] = 'ID';
1153 - $args[ 'order' ] = 'DESC';
1154 - break;
1155 - case 'least_recent':
1156 - $args[ 'orderby' ] = 'ID';
1157 - $args[ 'order' ] = 'ASC';
1158 - break;
1159 - case 'a_to_z':
1160 - $args[ 'orderby' ] = 'title';
1161 - $args[ 'order' ] = 'ASC';
1162 - break;
1163 - case 'z_to_a':
1164 - $args[ 'orderby' ] = 'title';
1165 - $args[ 'order' ] = 'DESC';
1166 - break;
1167 - case 'default':
1168 - case 'most_questions':
1169 - default:
1170 - $args[ 'orderby' ] = 'post__in';
1171 - $args[ 'post__in' ] = $this->get_faq_orders( $term_id );
1172 - break;
1173 - }
1049 + if ( ! empty( $post_ids ) ) {
1050 + if ( current_user_can( 'read_private_docs' ) ) {
1051 + // For users with read_private_docs capability, include both private and public posts
1052 + $filtered_post_ids = array_filter( $post_ids, function( $post_id ) {
1053 + $post_status = get_post_status( $post_id );
1054 + return $post_status === 'private' || is_post_publicly_viewable( $post_id );
1055 + });
1056 + } else {
1057 + // For users without read_private_docs capability, only include public posts
1058 + $filtered_post_ids = array_filter( $post_ids, function( $post_id ) {
1059 + return is_post_publicly_viewable( $post_id );
1060 + });
1061 + }
1174 1062
1175 - return new WP_Query( $args );
1176 - }
1063 + $counts = count( $filtered_post_ids );
1064 + } else {
1065 + $counts = 0;
1066 + }
1067 + }
1177 1068
1178 - public function get_faq_orders( $term_id = null ) {
1179 - global $wpdb;
1180 - $faq_order = get_term_meta( $term_id, '_betterdocs_faq_order', true );
1181 - $faq_order = explode( ',', $faq_order );
1069 + return apply_filters( 'betterdocs_docs_count', $counts, $term, $nested_subcategory, $args );
1070 + }
1182 1071
1183 - $query = $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}term_relationships WHERE term_taxonomy_id = %d", $term_id );
1184 - $query_key = 'betterdocs_faq_order_' . md5( $query );
1072 + $_child_terms_docs_ids = $this->get_doc_ids_by_term( $term, null, $nested_subcategory );
1073 + if ( is_array( $_child_terms_docs_ids ) ) {
1074 + $counts = count( $_child_terms_docs_ids );
1075 + }
1185 1076
1186 - if ( ( $results = $this->database->get_cache( $query_key ) ) !== false ) {
1187 - return $results;
1188 - }
1077 + return apply_filters( 'betterdocs_docs_count', $counts, $term, $nested_subcategory, $args );
1078 + }
1189 1079
1190 - if ( ! empty( $faq_order ) ) {
1191 - $new_ids = array();
1192 - // $query is prepared upstream; results are cached via $this->database->get_cache above (line 980).
1193 - $results = $wpdb->get_results( $query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1080 + public function get_doc_ids_by_term( $term, $optional = null, $nested_subcategory = false ) {
1081 + // Check if term has required properties and is a valid object
1082 + if ( ! is_object( $term ) || ! isset( $term->term_id ) || ! isset( $term->taxonomy ) || ! is_numeric( $term->term_id ) ) {
1083 + return false;
1084 + }
1194 1085
1195 - if ( ! is_null( $results ) && ! empty( $results ) && is_array( $results ) ) {
1196 - $object_ids = array_filter(
1197 - $results,
1198 - function ( $value ) use ( $faq_order ) {
1199 - return ! in_array( $value->object_id, $faq_order );
1200 - }
1201 - );
1202 -
1203 - if ( ! empty( $object_ids ) ) {
1204 - array_walk(
1205 - $object_ids,
1206 - function ( $value ) use ( &$new_ids ) {
1207 - $new_ids[ ] = $value->object_id;
1208 - }
1209 - );
1210 - }
1211 - }
1212 -
1213 - $faq_order = array_merge( $new_ids, $faq_order );
1214 - }
1215 -
1216 - $this->database->set_cache( $query_key, $faq_order, 1 );
1217 -
1218 - return $faq_order;
1219 - }
1220 -
1221 - public function get_faq_terms( $terms = array(), $taxonomy = 'betterdocs_faq_category' ) {
1222 - $_terms = get_terms(
1223 - array(
1224 - 'taxonomy' => $taxonomy,
1225 - 'hide_empty' => true,
1226 - 'orderby' => 'name',
1227 - 'order' => 'ASC',
1228 - 'meta_query' => array(
1229 - array(
1230 - 'key' => 'status',
1231 - 'value' => 1,
1232 - 'compare' => '=='
1233 - )
1234 - )
1235 - )
1236 - );
1237 -
1238 - if ( ! is_wp_error( $_terms ) ) {
1239 - foreach ( $_terms as $term ) {
1240 - $terms[ $term->term_id ] = $term->name;
1241 - }
1242 - }
1243 -
1244 - return $terms;
1245 - }
1246 -
1247 - public function get_doc_terms( $terms = array() ) {
1248 - $_terms = get_terms(
1249 - array(
1250 - 'taxonomy' => 'doc_category',
1251 - 'hide_empty' => true,
1252 - 'orderby' => 'name',
1253 - 'order' => 'ASC'
1254 - )
1255 - );
1256 -
1257 - if ( ! is_wp_error( $_terms ) ) {
1258 - foreach ( $_terms as $term ) {
1259 - $terms[ $term->term_id ] = $term->name;
1260 - }
1261 - }
1262 -
1263 - return $terms;
1264 - }
1265 -
1266 - public function flush_term_counts_cache() {
1267 - $this->database->bump_cache_version( 'betterdocs_term_counts' );
1268 - }
1269 -
1270 - public function flush_term_counts_cache_on_post( $post_id, $post = null ) {
1271 - if ( $post && isset( $post->post_type ) && $post->post_type === 'docs' ) {
1272 - $this->flush_term_counts_cache();
1273 - }
1274 - }
1275 -
1276 - public function flush_term_counts_cache_on_set( $object_id, $terms, $tt_ids, $taxonomy ) {
1277 - if ( $taxonomy === 'doc_category' ) {
1278 - $this->flush_term_counts_cache();
1279 - }
1280 - }
1281 -
1282 - public function get_docs_count( $term, $nested_subcategory = false, $args = array() ) {
1283 - // Validate term object
1284 - if ( ! is_object( $term ) ) {
1285 - return 0;
1286 - }
1287 -
1288 - $counts = isset( $term->count ) ? $term->count : 0;
1289 -
1290 - if ( ! isset( $term->term_id ) || ! is_numeric( $term->term_id ) ) {
1291 - return apply_filters( 'betterdocs_docs_count', $counts, $term, $nested_subcategory, $args );
1292 - }
1293 -
1294 - $version = $this->database->get_cache_version( 'betterdocs_term_counts' );
1295 - // Counts depend on who is asking: an author sees their own private docs, so the
1296 - // key carries the user id. Logged-out visitors all share user 0.
1297 - $viewer = $this->count_cache_viewer_key();
1298 - $kb_slug = isset( $args['kb_slug'] ) ? $args['kb_slug'] : '';
1299 - $multi = ! empty( $args['multiple_knowledge_base'] ) ? 1 : 0;
1300 - $nested = $nested_subcategory ? 1 : 0;
1301 - $cache_key = "bd_term_counts_v{$version}_docs_count_{$term->term_id}_{$nested}_{$viewer}_{$kb_slug}_{$multi}";
1302 -
1303 - $cached = wp_cache_get( $cache_key, 'betterdocs' );
1304 - if ( false !== $cached ) {
1305 - return apply_filters( 'betterdocs_docs_count', $cached, $term, $nested_subcategory, $args );
1306 - }
1307 -
1308 - if ( false == $nested_subcategory ) {
1309 - // For non-nested categories, we need to recalculate counts based on user capabilities
1310 - // Only proceed if we have a valid term with required properties
1311 - if ( isset( $term->taxonomy ) ) {
1312 - // Get all post IDs for this term
1313 - $post_ids = get_objects_in_term( $term->term_id, $term->taxonomy );
1314 -
1315 - if ( ! empty( $post_ids ) ) {
1316 - _prime_post_caches( $post_ids, false, false );
1317 -
1318 - // Public docs for everyone, plus any private doc this user may read
1319 - // (its own author, or a `read_private_docs` holder).
1320 - $filtered_post_ids = array_filter( $post_ids, function ( $post_id ) {
1321 - return $this->can_read_doc( $post_id );
1322 - } );
1323 -
1324 - $counts = count( $filtered_post_ids );
1325 - } else {
1326 - $counts = 0;
1327 - }
1328 - }
1329 - } else {
1330 - $_child_terms_docs_ids = $this->get_doc_ids_by_term( $term, null, $nested_subcategory );
1331 - if ( is_array( $_child_terms_docs_ids ) ) {
1332 - $counts = count( $_child_terms_docs_ids );
1333 - }
1334 - }
1335 -
1336 - wp_cache_set( $cache_key, $counts, 'betterdocs', HOUR_IN_SECONDS * 6 );
1337 -
1338 - return apply_filters( 'betterdocs_docs_count', $counts, $term, $nested_subcategory, $args );
1339 - }
1340 -
1341 - public function get_doc_ids_by_term( $term, $optional = null, $nested_subcategory = false ) {
1342 - // Check if term has required properties and is a valid object
1343 - if ( ! is_object( $term ) || ! isset( $term->term_id ) || ! isset( $term->taxonomy ) || ! is_numeric( $term->term_id ) ) {
1344 - return false;
1345 - }
1346 -
1347 - $version = $this->database->get_cache_version( 'betterdocs_term_counts' );
1348 - $viewer = $this->count_cache_viewer_key();
1349 - $nested = $nested_subcategory ? 1 : 0;
1350 - $optional_id = is_object( $optional ) && isset( $optional->term_id ) ? (int) $optional->term_id : 0;
1351 - $cache_key = "bd_term_counts_v{$version}_doc_ids_{$term->term_id}_{$nested}_{$optional_id}_{$viewer}";
1352 -
1353 - $cached = wp_cache_get( $cache_key, 'betterdocs' );
1354 - if ( false !== $cached ) {
1355 - return $cached;
1356 - }
1357 -
1358 - $args = array(
1359 - 'taxonomy' => $term->taxonomy,
1360 - 'include' => $term->term_id,
1361 - );
1086 + $args = ['include' => $term->term_id];
1362 1087 if ( $nested_subcategory ) {
1363 - $args[ 'child_of' ] = $term->term_id;
1364 - unset( $args[ 'include' ] );
1088 + $args['child_of'] = $term->term_id;
1089 + unset( $args['include'] );
1365 1090 }
1366 - $_child_terms = get_terms( $args );
1091 + $_child_terms = get_terms( $term->taxonomy, $args );
1367 1092
1368 1093 if ( ! is_array( $_child_terms ) ) {
1369 1094 return false;
1370 1095 }
@@ -1374,261 +1099,252 @@
1374 1099 $_child_terms_ids = array_column( $_child_terms, 'term_id' );
1375 1100 $_child_terms_taxs = array_column( $_child_terms, 'taxonomy' );
1376 1101 $_child_terms_docs_ids = get_objects_in_term( $_child_terms_ids, $_child_terms_taxs );
1377 1102
1378 - if ( null !== $optional ) {
1103 + if ( $optional !== null ) {
1379 1104 $_optional_doc_ids = get_objects_in_term( $optional->term_id, $optional->taxonomy );
1380 1105 $_child_terms_docs_ids = array_intersect( $_child_terms_docs_ids, $_optional_doc_ids );
1381 1106 }
1382 1107
1383 - if ( ! empty( $_child_terms_docs_ids ) ) {
1384 - _prime_post_caches( $_child_terms_docs_ids, false, false );
1385 - }
1108 + return array_filter( $_child_terms_docs_ids, function ( $doc_id ) {
1109 + if ( ! current_user_can( 'read_private_docs' ) ) {
1110 + return is_post_publicly_viewable( $doc_id );
1111 + }
1386 1112
1387 - $filtered = array_filter( $_child_terms_docs_ids, function ( $doc_id ) {
1388 - return $this->can_read_doc( $doc_id );
1113 + $_status = get_post_status( $doc_id );
1114 + return $_status == 'private' || is_post_publicly_viewable( $doc_id );
1389 1115 } );
1116 + }
1390 1117
1391 - wp_cache_set( $cache_key, $filtered, 'betterdocs', HOUR_IN_SECONDS * 6 );
1118 + /**
1119 + * Get the common query arguments for WP_Query.
1120 + *
1121 + * @param string $terms The taxonomy.
1122 + * @param string $term_slug The taxonomy term slug.
1123 + * @param array $additional_args Additional arguments to merge with the common arguments.
1124 + * @return array The query arguments.
1125 + */
1126 + private function tax_query_args( $terms, $term_slug, $additional_args = array() ) {
1127 + $common_args = array(
1128 + 'post_type' => 'docs',
1129 + 'post_status' => 'publish',
1130 + 'tax_query' => array(
1131 + array(
1132 + 'taxonomy' => $terms,
1133 + 'field' => 'slug',
1134 + 'terms' => $term_slug,
1135 + ),
1136 + ),
1137 + );
1138 + return array_merge( $common_args, $additional_args );
1139 + }
1392 1140
1393 - return $filtered;
1394 - }
1141 + /**
1142 + * Get the latest updated date for a specific taxonomy term.
1143 + *
1144 + * @param string $terms The taxonomy.
1145 + * @param string $term_slug The taxonomy term slug.
1146 + * @return string|null The latest modified date or null if no posts found.
1147 + */
1148 + public function latest_updated_date( $terms, $term_slug ) {
1149 + $args = $this->tax_query_args(
1150 + $terms,
1151 + $term_slug,
1152 + array(
1153 + 'posts_per_page' => 1,
1154 + 'orderby' => 'modified',
1155 + 'order' => 'DESC',
1156 + )
1157 + );
1395 1158
1396 - /**
1397 - * Get the common query arguments for WP_Query.
1398 - *
1399 - * @param string $terms The taxonomy.
1400 - * @param string $term_slug The taxonomy term slug.
1401 - * @param array $additional_args Additional arguments to merge with the common arguments.
1402 - * @return array The query arguments.
1403 - */
1404 - private function tax_query_args( $terms, $term_slug, $additional_args = array() ) {
1405 - $common_args = array(
1406 - 'post_type' => 'docs',
1407 - 'post_status' => 'publish',
1408 - 'tax_query' => array(
1409 - array(
1410 - 'taxonomy' => $terms,
1411 - 'field' => 'slug',
1412 - 'terms' => $term_slug
1413 - )
1414 - )
1415 - );
1416 - return array_merge( $common_args, $additional_args );
1417 - }
1159 + $query = new WP_Query( $args );
1418 1160
1419 - /**
1420 - * Get the latest updated date for a specific taxonomy term.
1421 - *
1422 - * @param string $terms The taxonomy.
1423 - * @param string $term_slug The taxonomy term slug.
1424 - * @return string|null The latest modified date or null if no posts found.
1425 - */
1426 - public function latest_updated_date( $terms, $term_slug ) {
1427 - $args = $this->tax_query_args(
1428 - $terms,
1429 - $term_slug,
1430 - array(
1431 - 'posts_per_page' => 1,
1432 - 'orderby' => 'modified',
1433 - 'order' => 'DESC'
1434 - )
1435 - );
1161 + if ( $query->have_posts() ) {
1162 + while ( $query->have_posts() ) {
1163 + $query->the_post();
1164 + $latest_post = get_the_modified_date();
1165 + wp_reset_postdata();
1166 + return $latest_post;
1167 + }
1168 + } else {
1169 + return null;
1170 + }
1171 + }
1436 1172
1437 - $query = new WP_Query( $args );
1173 + /**
1174 + * Check if there are any new posts within the last 7 days for a specific taxonomy term.
1175 + *
1176 + * @param string $terms The taxonomy.
1177 + * @param string $term_slug The taxonomy term slug.
1178 + * @return bool True if there are new posts, false otherwise.
1179 + */
1180 + public function check_new_posts( $terms, $term_slug ) {
1181 + $date_7_days_ago = date( 'Y-m-d H:i:s', strtotime( '-7 days' ) );
1438 1182
1439 - if ( $query->have_posts() ) {
1440 - while ( $query->have_posts() ) {
1441 - $query->the_post();
1442 - $latest_post = get_the_modified_date();
1443 - wp_reset_postdata();
1444 - return $latest_post;
1445 - }
1446 - } else {
1447 - return null;
1448 - }
1449 - }
1183 + $args = $this->tax_query_args(
1184 + $terms,
1185 + $term_slug,
1186 + array(
1187 + 'posts_per_page' => 1,
1188 + 'orderby' => 'modified',
1189 + 'order' => 'DESC',
1190 + 'date_query' => array(
1191 + array(
1192 + 'after' => $date_7_days_ago,
1193 + 'inclusive' => true,
1194 + ),
1195 + ),
1196 + )
1197 + );
1450 1198
1451 - /**
1452 - * Check if there are any new posts within the last 7 days for a specific taxonomy term.
1453 - *
1454 - * @param string $terms The taxonomy.
1455 - * @param string $term_slug The taxonomy term slug.
1456 - * @return bool True if there are new posts, false otherwise.
1457 - */
1458 - public function check_new_posts( $terms, $term_slug ) {
1459 - $date_7_days_ago = gmdate( 'Y-m-d H:i:s', strtotime( '-7 days' ) );
1199 + $query = new WP_Query( $args );
1460 1200
1461 - $args = $this->tax_query_args(
1462 - $terms,
1463 - $term_slug,
1464 - array(
1465 - 'posts_per_page' => 1,
1466 - 'orderby' => 'modified',
1467 - 'order' => 'DESC',
1468 - 'date_query' => array(
1469 - array(
1470 - 'after' => $date_7_days_ago,
1471 - 'inclusive' => true
1472 - )
1473 - )
1474 - )
1475 - );
1201 + $has_new_posts = $query->have_posts();
1476 1202
1477 - $query = new WP_Query( $args );
1203 + wp_reset_postdata();
1478 1204
1479 - $has_new_posts = $query->have_posts();
1205 + return $has_new_posts;
1206 + }
1480 1207
1481 - wp_reset_postdata();
1208 + public function insert_search_keyword( $search_input, $input_not_found ) {
1209 + if ( empty( $search_input ) ) {
1210 + return false;
1211 + }
1482 1212
1483 - return $has_new_posts;
1484 - }
1485 -
1486 - public function insert_search_keyword( $search_input, $input_not_found ) {
1487 - if ( empty( $search_input ) ) {
1488 - return false;
1489 - }
1490 -
1491 - global $wpdb;
1492 -
1493 - // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- live search-keyword analytics; cache would defeat the purpose.
1494 - // Use BINARY comparison to avoid collation mismatch errors
1495 - // This works across all character sets (latin1, utf8, utf8mb4, etc.)
1496 - $search = $wpdb->get_results(
1497 - $wpdb->prepare(
1498 - "SELECT *
1213 + global $wpdb;
1214 + $search = $wpdb->get_results(
1215 + $wpdb->prepare(
1216 + "SELECT *
1499 1217 FROM {$wpdb->prefix}betterdocs_search_keyword
1500 - WHERE BINARY keyword = %s",
1501 - $search_input
1502 - )
1503 - );
1218 + WHERE keyword = %s",
1219 + $search_input
1220 + )
1221 + );
1504 1222
1505 - if ( ! empty( $search ) ) {
1506 - $search_log = $wpdb->get_results(
1507 - $wpdb->prepare(
1508 - "SELECT *
1223 + if ( ! empty( $search ) ) {
1224 + $search_log = $wpdb->get_results(
1225 + $wpdb->prepare(
1226 + "SELECT *
1509 1227 FROM {$wpdb->prefix}betterdocs_search_log
1510 1228 WHERE created_at = %s AND keyword_id = %d",
1511 - gmdate( 'Y-m-d' ),
1512 - $search[ 0 ]->id
1513 - )
1514 - );
1229 + date( 'Y-m-d' ),
1230 + $search[0]->id
1231 + )
1232 + );
1515 1233
1516 - if ( ! empty( $search_log ) ) {
1517 - if ( ! empty( $input_not_found ) ) {
1518 - $tbl_field = 'not_found_count';
1519 - $count = $search_log[ 0 ]->not_found_count + 1;
1520 - } else {
1521 - $tbl_field = 'count';
1522 - $count = $search_log[ 0 ]->count + 1;
1523 - }
1524 - // $tbl_field is validated immediately above to be either 'count' or
1525 - // 'not_found_count' — safe to interpolate as a column identifier.
1526 - // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- $tbl_field is an allowlisted column name ('count'|'not_found_count'); safe to interpolate.
1527 - $insert = $wpdb->query(
1528 - $wpdb->prepare(
1529 - "UPDATE {$wpdb->prefix}betterdocs_search_log SET {$tbl_field} = %d WHERE created_at = %s AND keyword_id = %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
1530 - $count,
1531 - $search_log[ 0 ]->created_at,
1532 - $search_log[ 0 ]->keyword_id
1533 - )
1534 - );
1535 - } else {
1536 - if ( ! empty( $input_not_found ) ) {
1537 - $count = 0;
1538 - $not_found_count = 1;
1539 - } else {
1540 - $count = 1;
1541 - $not_found_count = 0;
1542 - }
1543 - $insert = $wpdb->query(
1544 - $wpdb->prepare(
1545 - "INSERT INTO {$wpdb->prefix}betterdocs_search_log
1234 + if ( ! empty( $search_log ) ) {
1235 + if ( ! empty( $input_not_found ) ) {
1236 + $tbl_field = 'not_found_count';
1237 + $count = $search_log[0]->not_found_count + 1;
1238 + } else {
1239 + $tbl_field = 'count';
1240 + $count = $search_log[0]->count + 1;
1241 + }
1242 + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
1243 + $insert = $wpdb->query(
1244 + $wpdb->prepare(
1245 + "UPDATE {$wpdb->prefix}betterdocs_search_log
1246 + SET " . $tbl_field . ' = ' . $count . '
1247 + WHERE created_at = %s AND keyword_id = %d',
1248 + $search_log[0]->created_at,
1249 + $search_log[0]->keyword_id
1250 + )
1251 + );
1252 + } else {
1253 + if ( ! empty( $input_not_found ) ) {
1254 + $count = 0;
1255 + $not_found_count = 1;
1256 + } else {
1257 + $count = 1;
1258 + $not_found_count = 0;
1259 + }
1260 + $insert = $wpdb->query(
1261 + $wpdb->prepare(
1262 + "INSERT INTO {$wpdb->prefix}betterdocs_search_log
1546 1263 ( keyword_id, count, not_found_count, created_at )
1547 1264 VALUES ( %d, %d, %d, %s )",
1548 - array(
1549 - $search[ 0 ]->id,
1550 - $count,
1551 - $not_found_count,
1552 - gmdate( 'Y-m-d' )
1553 - )
1554 - )
1555 - );
1556 - }
1557 - } else {
1558 - $insert = $wpdb->query(
1559 - $wpdb->prepare(
1560 - "INSERT INTO {$wpdb->prefix}betterdocs_search_keyword
1265 + [
1266 + $search[0]->id,
1267 + $count,
1268 + $not_found_count,
1269 + date( 'Y-m-d' )
1270 + ]
1271 + )
1272 + );
1273 + }
1274 + } else {
1275 + $insert = $wpdb->query(
1276 + $wpdb->prepare(
1277 + "INSERT INTO {$wpdb->prefix}betterdocs_search_keyword
1561 1278 ( keyword )
1562 1279 VALUES ( %s )",
1563 - array(
1564 - $search_input
1565 - )
1566 - )
1567 - );
1280 + [
1281 + $search_input
1282 + ]
1283 + )
1284 + );
1568 1285
1569 - if ( $insert ) {
1570 - if ( ! empty( $input_not_found ) ) {
1571 - $count = 0;
1572 - $not_found_count = 1;
1573 - } else {
1574 - $count = 1;
1575 - $not_found_count = 0;
1576 - }
1577 - $insert = $wpdb->query(
1578 - $wpdb->prepare(
1579 - "INSERT INTO {$wpdb->prefix}betterdocs_search_log
1286 + if ( $insert ) {
1287 + if ( ! empty( $input_not_found ) ) {
1288 + $count = 0;
1289 + $not_found_count = 1;
1290 + } else {
1291 + $count = 1;
1292 + $not_found_count = 0;
1293 + }
1294 + $insert = $wpdb->query(
1295 + $wpdb->prepare(
1296 + "INSERT INTO {$wpdb->prefix}betterdocs_search_log
1580 1297 ( keyword_id, count, not_found_count, created_at )
1581 1298 VALUES ( %d, %d, %d, %s )",
1582 - array(
1583 - $wpdb->insert_id,
1584 - $count,
1585 - $not_found_count,
1586 - gmdate( 'Y-m-d' )
1587 - )
1588 - )
1589 - );
1590 - }
1591 - }
1592 - // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1593 - return $insert;
1594 - }
1299 + [
1300 + $wpdb->insert_id,
1301 + $count,
1302 + $not_found_count,
1303 + date( 'Y-m-d' )
1304 + ]
1305 + )
1306 + );
1307 + }
1308 + }
1309 + return $insert;
1310 + }
1595 1311
1596 - /**
1597 - * Counts the number of 'doc_category' terms assigned to a specific 'knowledge_base' by slug.
1598 - *
1599 - * This method retrieves all terms in the 'doc_category' taxonomy and checks the term meta
1600 - * 'doc_category_knowledge_base' to determine how many 'doc_category' terms are associated
1601 - * with a given 'knowledge_base' slug.
1602 - *
1603 - * @param string $knowledge_base_slug The slug of the 'knowledge_base' to count the assignments for.
1604 - *
1605 - * @return int The count of 'doc_category' terms assigned to the specified 'knowledge_base'.
1606 - */
1607 - public function count_doc_categories_for_knowledge_base( $knowledge_base_slug ) {
1608 - $count = 0;
1312 + /**
1313 + * Counts the number of 'doc_category' terms assigned to a specific 'knowledge_base' by slug.
1314 + *
1315 + * This method retrieves all terms in the 'doc_category' taxonomy and checks the term meta
1316 + * 'doc_category_knowledge_base' to determine how many 'doc_category' terms are associated
1317 + * with a given 'knowledge_base' slug.
1318 + *
1319 + * @param string $knowledge_base_slug The slug of the 'knowledge_base' to count the assignments for.
1320 + *
1321 + * @return int The count of 'doc_category' terms assigned to the specified 'knowledge_base'.
1322 + */
1323 + public function count_doc_categories_for_knowledge_base( $knowledge_base_slug ) {
1324 + $count = 0;
1609 1325
1610 - $doc_categories = get_terms(
1611 - array(
1612 - 'taxonomy' => 'doc_category',
1613 - 'hide_empty' => true
1614 - )
1615 - );
1326 + $doc_categories = get_terms(
1327 + array(
1328 + 'taxonomy' => 'doc_category',
1329 + 'hide_empty' => true,
1330 + )
1331 + );
1616 1332
1617 - if ( ! empty( $doc_categories ) && ! is_wp_error( $doc_categories ) ) {
1618 - foreach ( $doc_categories as $term ) {
1619 - $meta_value = get_term_meta( $term->term_id, 'doc_category_knowledge_base', true );
1333 + if ( ! empty( $doc_categories ) && ! is_wp_error( $doc_categories ) ) {
1334 + foreach ( $doc_categories as $term ) {
1335 + $meta_value = get_term_meta( $term->term_id, 'doc_category_knowledge_base', true );
1620 1336
1621 - if ( $meta_value ) {
1622 - $knowledge_bases = maybe_unserialize( $meta_value );
1337 + if ( $meta_value ) {
1338 + $knowledge_bases = maybe_unserialize( $meta_value );
1623 1339
1624 - // Check if the specific knowledge base slug is present in the meta value array
1625 - if ( is_array( $knowledge_bases ) && in_array( $knowledge_base_slug, $knowledge_bases ) ) {
1626 - ++$count;
1627 - }
1628 - }
1629 - }
1630 - }
1340 + // Check if the specific knowledge base slug is present in the meta value array
1341 + if ( is_array( $knowledge_bases ) && in_array( $knowledge_base_slug, $knowledge_bases ) ) {
1342 + ++$count;
1343 + }
1344 + }
1345 + }
1346 + }
1631 1347
1632 - return $count;
1633 - }
1348 + return $count;
1349 + }
1634 1350 }