PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.9.3
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.9.3
4.9.3 4.9.2 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 All 201 releases
← All changes | includes/Core/Request.php +503 -33 4.4.1 → 4.9.3 View file →
@@ -1,9 +1,14 @@
1 1 <?php
2 +namespace WPDeveloper\BetterDocs\Core;
2 3
3 -namespace WPDeveloper\BetterDocs\Core;
4 +if ( ! defined( 'ABSPATH' ) ) {
5 + exit;
6 +}
4 7
8 +
5 9 use WPDeveloper\BetterDocs\Utils\Base;
10 +use WPDeveloper\BetterDocs\Utils\Helper;
6 11
7 12 class Request extends Base {
8 13 /**
9 14 * Flag for already parsed or not
@@ -147,8 +152,15 @@
147 152 * Hook into template_redirect to validate category-post relationships
148 153 * Priority 0 to run before WordPress canonical redirect (priority 10)
149 154 */
150 155 add_action( 'template_redirect', [ $this, 'validate_single_docs_category_redirect' ], 0 );
156 +
157 + /**
158 + * Hook into template_redirect to 301 non-canonical single doc URLs.
159 + * Priority 5: after the validation above (0) so requests already headed for
160 + * a 404 are left alone, and before WordPress canonical redirect (10).
161 + */
162 + add_action( 'template_redirect', [ $this, 'redirect_to_canonical_docs_url' ], 5 );
151 163 }
152 164
153 165 public function provide_compatibility( $element_id, $uri_parts, $request_url ) {
154 166 if ( $request_url == $this->settings->get( 'docs_slug' ) ) {
@@ -215,9 +227,9 @@
215 227 if ( $this->invalid_request_query_vars !== null ) {
216 228 return false; // Block the redirect, show 404 instead
217 229 }
218 230
219 - $actual_url = home_url( $_SERVER['REQUEST_URI'] ?? '' );
231 + $actual_url = home_url( isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '' );
220 232
221 233 // Legacy check: if post_type=docs is already set in query vars, validate category
222 234 if ( isset( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] === 'docs' &&
223 235 isset( $wp_query->query_vars['doc_category'] ) && isset( $wp_query->query_vars['name'] ) ) {
@@ -333,11 +345,14 @@
333 345 }, 999 );
334 346 return;
335 347 }
336 348
337 - // Legacy check: if post_type=docs is already set in query vars, validate category
349 + // Legacy check: if post_type=docs is already set in query vars, validate category.
350 + // `name` must be a non-empty string — WP populates it with '' for taxonomy archive
351 + // requests (e.g. comma-separated multi-category URLs like /docs-category/a,b/),
352 + // which `isset()` would treat as present and incorrectly trigger this single-doc branch.
338 353 if ( isset( $wp_query->query_vars['post_type'] ) && $wp_query->query_vars['post_type'] === 'docs' &&
339 - isset( $wp_query->query_vars['doc_category'] ) && isset( $wp_query->query_vars['name'] ) ) {
354 + isset( $wp_query->query_vars['doc_category'] ) && ! empty( $wp_query->query_vars['name'] ) ) {
340 355
341 356 $doc_category = $wp_query->query_vars['doc_category'];
342 357 $post_name = $wp_query->query_vars['name'];
343 358
@@ -342,9 +357,9 @@
342 357 $post_name = $wp_query->query_vars['name'];
343 358
344 359 // Get the post
345 360 $post = get_page_by_path( $post_name, OBJECT, 'docs' );
346 -
361 +
347 362 if ( ! $post ) {
348 363 $wp_query->set_404();
349 364 status_header( 404 );
350 365 nocache_headers();
@@ -387,8 +402,225 @@
387 402 }
388 403 }
389 404
390 405 /**
406 + * 301 redirect a single doc to its canonical permalink.
407 + *
408 + * With `enable_category_hierarchy_slugs` enabled the single doc rewrite rule
409 + * captures every segment between the base and the doc slug into `doc_category`
410 + * (see Rewrite::rules), and the category validation above only requires ONE of
411 + * those segments to match. That looseness is deliberate — a strict match would
412 + * 404 legitimate Multiple KB and WPML URLs, where the KB slug and translated
413 + * segments share the same capture group — but it also means a doc resolves on an
414 + * unlimited number of URLs, e.g. /docs/anything/real-category/doc-slug/.
415 + *
416 + * Rather than tightening the match, this compares the requested category path
417 + * against every path the doc legitimately has and redirects the rest. Every URL
418 + * that resolves today keeps resolving; only the extra ones collapse.
419 + */
420 + public function redirect_to_canonical_docs_url() {
421 + global $wp_query;
422 +
423 + /**
424 + * Allow the canonical redirect to be disabled.
425 + *
426 + * @param bool $enabled Whether non-canonical single doc URLs should 301.
427 + */
428 + if ( ! apply_filters( 'betterdocs_enable_canonical_redirect', true ) ) {
429 + return;
430 + }
431 +
432 + if ( is_admin() || wp_doing_ajax() || is_feed() || is_embed() || is_preview() || is_customize_preview() ) {
433 + return;
434 + }
435 +
436 + $request_method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) : 'GET';
437 + if ( $request_method !== 'GET' ) {
438 + return;
439 + }
440 +
441 + if ( ! is_singular( 'docs' ) || is_404() ) {
442 + return;
443 + }
444 +
445 + /**
446 + * The request is already headed for a 404 — leave it alone. Note that
447 + * prevent_any_redirect_for_invalid_docs() cancels every wp_redirect() while
448 + * this flag is set, so the redirect below would be swallowed anyway.
449 + */
450 + if ( $this->invalid_request_query_vars !== null ) {
451 + return;
452 + }
453 +
454 + $requested_category = isset( $wp_query->query_vars['doc_category'] ) ? $wp_query->query_vars['doc_category'] : '';
455 + if ( ! is_string( $requested_category ) || $requested_category === '' ) {
456 + return;
457 + }
458 +
459 + $post_id = get_queried_object_id();
460 + if ( ! $post_id ) {
461 + return;
462 + }
463 +
464 + $valid_paths = $this->get_valid_category_paths( $post_id );
465 + if ( empty( $valid_paths ) ) {
466 + return;
467 + }
468 +
469 + $requested_category = urldecode( trim( $requested_category, '/' ) );
470 +
471 + /**
472 + * Under Multiple KB the knowledge base segment is parsed into its own query
473 + * var, so put it back in front of the category chain before comparing —
474 + * otherwise a crossed `/kb-a/category-of-kb-b/doc/` would look canonical.
475 + */
476 + $requested_kb = isset( $wp_query->query_vars['knowledge_base'] ) ? $wp_query->query_vars['knowledge_base'] : '';
477 + if ( is_string( $requested_kb ) && $requested_kb !== '' ) {
478 + $requested_category = urldecode( trim( $requested_kb, '/' ) ) . '/' . $requested_category;
479 + }
480 +
481 + if ( in_array( $requested_category, $valid_paths, true ) ) {
482 + return; // Already canonical (or another legitimate category of this doc).
483 + }
484 +
485 + $canonical = get_permalink( $post_id );
486 + if ( ! $canonical ) {
487 + return;
488 + }
489 +
490 + // Keep the multipage segment the rewrite rule captured.
491 + $page = isset( $wp_query->query_vars['page'] ) ? absint( $wp_query->query_vars['page'] ) : 0;
492 + if ( $page > 1 ) {
493 + $canonical = trailingslashit( $canonical ) . user_trailingslashit( $page, 'single_paged' );
494 + }
495 +
496 + /**
497 + * Belt and braces: never redirect a URL onto itself. The allowed set is built
498 + * from the same term chains get_permalink() uses, so this should be
499 + * unreachable, but a third party filtering the permalink could otherwise turn
500 + * a redirect into a loop.
501 + */
502 + $requested_path = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
503 + $canonical_path = wp_parse_url( $canonical, PHP_URL_PATH );
504 + if ( untrailingslashit( urldecode( (string) $requested_path ) ) === untrailingslashit( urldecode( (string) $canonical_path ) ) ) {
505 + return;
506 + }
507 +
508 + $query_string = isset( $_SERVER['QUERY_STRING'] ) ? sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) : '';
509 + if ( $query_string !== '' ) {
510 + $canonical .= ( strpos( $canonical, '?' ) === false ? '?' : '&' ) . $query_string;
511 + }
512 +
513 + if ( wp_safe_redirect( $canonical, 301 ) ) {
514 + exit;
515 + }
516 + }
517 +
518 + /**
519 + * Every category path a doc can legitimately be reached at.
520 + *
521 + * Includes the full parent/child chain of each assigned category, and — because
522 + * the hierarchy rewrite rule folds the knowledge base slug into `doc_category`
523 + * for the `docs/%knowledge_base%/%doc_category%` structure — the KB-prefixed
524 + * variants too.
525 + *
526 + * @param int $post_id The doc id.
527 + * @return string[] Normalised (urldecoded, unslashed) category paths.
528 + */
529 + protected function get_valid_category_paths( $post_id ) {
530 + $cat_terms = wp_get_object_terms( $post_id, 'doc_category' );
531 +
532 + if ( is_wp_error( $cat_terms ) ) {
533 + return [];
534 + }
535 +
536 + $paths = [];
537 + $cat_paths = [];
538 +
539 + if ( empty( $cat_terms ) ) {
540 + $paths[] = 'uncategorized';
541 + } else {
542 + foreach ( $cat_terms as $cat_term ) {
543 + $path = PostType::build_category_path( $cat_term );
544 +
545 + if ( $path !== '' ) {
546 + $paths[] = $path;
547 + $cat_paths[ $cat_term->term_id ] = $path;
548 + }
549 + }
550 + }
551 +
552 + if ( taxonomy_exists( 'knowledge_base' ) ) {
553 + $kb_terms = wp_get_object_terms( $post_id, 'knowledge_base', [ 'fields' => 'slugs' ] );
554 +
555 + if ( ! is_wp_error( $kb_terms ) && ! empty( $kb_terms ) ) {
556 + $kb_paths = [];
557 +
558 + /**
559 + * Read the KB association once per category rather than once per
560 + * KB/category pair. The wp_get_object_terms() call above primes the
561 + * term meta cache for these terms (`update_term_meta_cache` defaults
562 + * to true), so these reads are cache hits and add no queries.
563 + *
564 + * The association mirrors how PostType::post_link() picks the
565 + * category via `doc_category_knowledge_base`. Without it a doc in
566 + * KB A / category A and KB B / category B would treat the crossed
567 + * `/kb-a/category-b/doc/` as canonical. A term with no association
568 + * meta is unassigned rather than KB specific, so it stays valid
569 + * under every KB — post_link() falls back the same way.
570 + */
571 + $term_kbs = [];
572 +
573 + if ( ! empty( $cat_paths ) ) {
574 + foreach ( array_keys( $cat_paths ) as $term_id ) {
575 + $meta = get_term_meta( $term_id, 'doc_category_knowledge_base', true );
576 + $term_kbs[ $term_id ] = ( ! empty( $meta ) && is_array( $meta ) ) ? $meta : null;
577 + }
578 + }
579 +
580 + foreach ( $kb_terms as $kb_slug ) {
581 + if ( empty( $cat_paths ) ) {
582 + // Uncategorised doc: the KB slug is the only prefix there is.
583 + foreach ( $paths as $path ) {
584 + $kb_paths[] = $kb_slug . '/' . $path;
585 + }
586 + continue;
587 + }
588 +
589 + foreach ( $cat_paths as $term_id => $path ) {
590 + if ( $term_kbs[ $term_id ] !== null && ! in_array( $kb_slug, $term_kbs[ $term_id ], true ) ) {
591 + continue;
592 + }
593 +
594 + $kb_paths[] = $kb_slug . '/' . $path;
595 + }
596 + }
597 +
598 + $paths = array_merge( $paths, $kb_paths );
599 + }
600 + }
601 +
602 + /**
603 + * Non-Latin slugs are stored URL encoded while the requested path arrives
604 + * decoded, so normalise both sides before comparing.
605 + */
606 + $paths = array_map(
607 + function ( $path ) {
608 + return urldecode( trim( $path, '/' ) );
609 + },
610 + $paths
611 + );
612 +
613 + /**
614 + * Filter the category paths a doc is allowed to be reached at.
615 + *
616 + * @param string[] $paths Valid category paths.
617 + * @param int $post_id The doc id.
618 + */
619 + return array_values( array_unique( apply_filters( 'betterdocs_valid_docs_category_paths', $paths, $post_id ) ) );
620 + }
621 +
622 + /**
391 623 * Check if a URL matches a BetterDocs single docs permalink structure
392 624 * but has invalid KB/category slugs that don't match the post.
393 625 *
394 626 * @param string $url The URL to check.
@@ -395,9 +627,9 @@
395 627 * @return bool True if the URL is a BetterDocs docs URL with invalid slugs.
396 628 */
397 629 protected function is_invalid_docs_url( $url ) {
398 630 // Get the path from the URL
399 - $path = trim( parse_url( $url, PHP_URL_PATH ), '/' );
631 + $path = trim( (string) wp_parse_url( $url, PHP_URL_PATH ), '/' );
400 632
401 633 // Check each permalink structure
402 634 foreach ( $this->perma_structure as $_type => $structure ) {
403 635 if ( $_type !== 'is_single_docs' ) {
@@ -620,18 +852,46 @@
620 852 }
621 853
622 854 // Check if request path strictly starts with docs slug, category slug, or tag slug
623 855 // Using # as delimiter, need to preg_quote
624 - $valid_prefixes = [
625 - preg_quote( $docs_slug, '#' ),
626 - preg_quote( trim( $this->settings->get( 'category_slug', 'docs-category' ), '/' ), '#' ),
627 - preg_quote( trim( $this->settings->get( 'tag_slug', 'docs-tag' ), '/' ), '#' )
856 + $valid_slugs = [
857 + $docs_slug,
858 + trim( $this->settings->get( 'category_slug', 'docs-category' ), '/' ),
859 + trim( $this->settings->get( 'tag_slug', 'docs-tag' ), '/' )
628 860 ];
629 - $valid_prefixes = array_filter( $valid_prefixes );
630 -
861 +
862 + // WPML/Polylang translate the registered rewrite slug per active language,
863 + // while $docs_slug from settings is always the default-language slug. Include
864 + // the post type's / taxonomies' currently-registered rewrite slugs so that
865 + // translated archive URLs (e.g. /en/support/ when settings.docs_slug is
866 + // "soporte") are accepted instead of being 404'd.
867 + $docs_pt = get_post_type_object( 'docs' );
868 + if ( $docs_pt && ! empty( $docs_pt->rewrite['slug'] ) ) {
869 + $valid_slugs[] = trim( $docs_pt->rewrite['slug'], '/' );
870 + }
871 + foreach ( [ 'doc_category', 'doc_tag', 'knowledge_base' ] as $tax ) {
872 + $tax_obj = get_taxonomy( $tax );
873 + if ( $tax_obj && ! empty( $tax_obj->rewrite['slug'] ) ) {
874 + $valid_slugs[] = trim( $tax_obj->rewrite['slug'], '/' );
875 + }
876 + }
877 +
878 + // Belt-and-suspenders for WPML's slug-translation feature, which may store
879 + // the translated slug separately from the post type's rewrite['slug'].
880 + if ( has_filter( 'wpml_get_translated_slug' ) ) {
881 + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WPML-owned filter; name must be used verbatim.
882 + $wpml_slug = apply_filters( 'wpml_get_translated_slug', $docs_slug, 'docs' );
883 + if ( is_string( $wpml_slug ) && $wpml_slug !== '' ) {
884 + $valid_slugs[] = trim( $wpml_slug, '/' );
885 + }
886 + }
887 +
888 + $valid_prefixes = array_unique( array_filter( $valid_slugs ) );
889 + $valid_prefixes = array_map( function ( $slug ) { return preg_quote( $slug, '#' ); }, $valid_prefixes );
890 +
631 891 // Allow optional language prefixes (e.g. /en/, /pt-br/) for WPML/Polylang/TranslatePress compatibility
632 892 $lang_pattern = '(?:[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,4})?/)?';
633 -
893 +
634 894 $prefix_pattern = '#^' . $lang_pattern . '(' . implode( '|', $valid_prefixes ) . ')(/|$)#';
635 895
636 896 if ( ! preg_match( $prefix_pattern, $request_path ) ) {
637 897 global $wp_query;
@@ -688,14 +948,40 @@
688 948
689 949 // Check if we have 'docs' query var (alternative to 'name')
690 950 if ( isset( $wp_query->query_vars['docs'] ) && ! empty( $wp_query->query_vars['docs'] ) ) {
691 951
952 + // Verify the requested doc actually exists (and is visible to the
953 + // current user) before forcing a single-doc render. Category-in-path
954 + // permalinks put the doc slug in the `docs` var alongside a valid
955 + // doc_category; without this guard a missing slug under a real
956 + // category rendered the single template against a null post — an
957 + // HTTP 200 soft-404 plus "read property on null" warnings on every
958 + // (often bot) hit. See betterdocs/betterdocs#169.
959 + $doc_post = get_page_by_path( $wp_query->query_vars['docs'], OBJECT, 'docs' );
960 + $doc_visible = $doc_post
961 + && ( 'private' !== $doc_post->post_status || current_user_can( 'read_private_docs' ) );
962 +
963 + if ( ! $doc_visible ) {
964 + // No such doc (or private and not permitted) — serve a genuine
965 + // 404 instead of a single render against a null post.
966 + $wp_query->set_404();
967 + status_header( 404 );
968 + nocache_headers();
969 + add_filter( 'template_include', function( $template ) {
970 + $not_found = get_404_template();
971 + return $not_found ? $not_found : $template;
972 + }, 999 );
973 + return;
974 + }
975 +
692 976 // Explicitly set this as a single post
693 - $wp_query->is_single = true;
694 - $wp_query->is_singular = true;
695 - $wp_query->is_404 = false;
696 - $wp_query->is_archive = false;
697 - $wp_query->is_tax = false;
977 + $wp_query->is_single = true;
978 + $wp_query->is_singular = true;
979 + $wp_query->is_404 = false;
980 + $wp_query->is_archive = false;
981 + $wp_query->is_tax = false;
982 + $wp_query->queried_object = $doc_post;
983 + $wp_query->queried_object_id = $doc_post->ID;
698 984 return;
699 985 }
700 986
701 987 // If 'name' is set, check if a post with that name exists
@@ -815,8 +1101,24 @@
815 1101 if ( $code == 404 && (
816 1102 (isset($wp_query->query_vars['doc_category']) && ! empty($wp_query->query_vars['doc_category'])) ||
817 1103 (isset($wp_query->query_vars['doc_tag']) && ! empty($wp_query->query_vars['doc_tag']))
818 1104 ) ) {
1105 + // A single-doc request (category-in-path permalinks carry the doc slug
1106 + // in the `docs`/`name` var alongside doc_category) must resolve to a real
1107 + // doc. A valid doc is already served 200 by the queried-object branch
1108 + // above; if we reach here with a single-doc indicator but no resolvable
1109 + // post, the doc does not exist — keep the genuine 404 rather than forcing
1110 + // a soft-404 200 off the category term alone. See betterdocs/betterdocs#169.
1111 + $single_doc_slug = '';
1112 + if ( isset( $wp_query->query_vars['docs'] ) && ! empty( $wp_query->query_vars['docs'] ) ) {
1113 + $single_doc_slug = $wp_query->query_vars['docs'];
1114 + } elseif ( isset( $wp_query->query_vars['name'] ) && ! empty( $wp_query->query_vars['name'] ) ) {
1115 + $single_doc_slug = $wp_query->query_vars['name'];
1116 + }
1117 + if ( '' !== $single_doc_slug && ! get_page_by_path( $single_doc_slug, OBJECT, 'docs' ) ) {
1118 + return $status_header;
1119 + }
1120 +
819 1121 // Validate existence before forcing 200
820 1122 // Use encoded fallback so Bengali/Arabic/CJK slugs are found correctly.
821 1123 if ( isset($wp_query->query_vars['doc_category']) && ! empty($wp_query->query_vars['doc_category']) ) {
822 1124 $term = $this->get_term_by_slug_or_encoded( $wp_query->query_vars['doc_category'], 'doc_category' );
@@ -932,8 +1234,9 @@
932 1234 if ( ! isset( $query_vars['name'] ) && ! isset( $query_vars['docs'] ) ) {
933 1235 return false;
934 1236 }
935 1237
1238 + // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- frontend single-doc URL resolution; queries vary per request and run on `parse_request`, before object cache is reliable.
936 1239 global $wpdb;
937 1240 $name = isset( $query_vars['docs'] ) ? $query_vars['docs'] : $query_vars['name'];
938 1241
939 1242
@@ -954,22 +1257,37 @@
954 1257 $_encoded_name = rawurlencode( $name );
955 1258
956 1259 if ( isset( $query_vars['knowledge_base'] ) && ! empty( $query_vars['knowledge_base'] ) ) {
957 1260 // KB-aware lookup: only select the post that is assigned to this KB.
1261 + // Also join doc_category when present so that, on Polylang/WPML sites
1262 + // where multiple translated posts share both the same post_name and
1263 + // the same KB term (e.g. all language variants assigned to the
1264 + // "advice" KB), we land on the translation whose doc_category matches
1265 + // the URL — not the one the DB happens to return first.
958 1266 $_kb_slug = $query_vars['knowledge_base'];
959 1267 $_kb_slug_enc = strtolower( rawurlencode( $_kb_slug ) );
1268 +
1269 + $_cat_target = $target_category_slug;
1270 + $_cat_target_enc = strtolower( rawurlencode( $_cat_target ) );
1271 +
960 1272 $_post_id = (int) $wpdb->get_var(
961 1273 $wpdb->prepare(
962 1274 "SELECT p.ID FROM {$wpdb->posts} p
963 - INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
964 - INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'knowledge_base'
965 - INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
1275 + INNER JOIN {$wpdb->term_relationships} tr_kb ON tr_kb.object_id = p.ID
1276 + INNER JOIN {$wpdb->term_taxonomy} tt_kb ON tt_kb.term_taxonomy_id = tr_kb.term_taxonomy_id AND tt_kb.taxonomy = 'knowledge_base'
1277 + INNER JOIN {$wpdb->terms} t_kb ON t_kb.term_id = tt_kb.term_id
1278 + INNER JOIN {$wpdb->term_relationships} tr_cat ON tr_cat.object_id = p.ID
1279 + INNER JOIN {$wpdb->term_taxonomy} tt_cat ON tt_cat.term_taxonomy_id = tr_cat.term_taxonomy_id AND tt_cat.taxonomy = 'doc_category'
1280 + INNER JOIN {$wpdb->terms} t_cat ON t_cat.term_id = tt_cat.term_id
966 1281 WHERE p.post_name = %s AND p.post_type = 'docs'
967 - AND t.slug IN (%s, %s)
1282 + AND t_kb.slug IN (%s, %s)
1283 + AND t_cat.slug IN (%s, %s)
968 1284 LIMIT 1",
969 1285 esc_sql( $_encoded_name ),
970 1286 esc_sql( $_kb_slug ),
971 - esc_sql( $_kb_slug_enc )
1287 + esc_sql( $_kb_slug_enc ),
1288 + esc_sql( $_cat_target_enc ),
1289 + esc_sql( $_cat_target )
972 1290 )
973 1291 );
974 1292 // Fallback: post_name stored as decoded Unicode
975 1293 if ( ! $_post_id && $_encoded_name !== $name ) {
@@ -975,8 +1293,35 @@
975 1293 if ( ! $_post_id && $_encoded_name !== $name ) {
976 1294 $_post_id = (int) $wpdb->get_var(
977 1295 $wpdb->prepare(
978 1296 "SELECT p.ID FROM {$wpdb->posts} p
1297 + INNER JOIN {$wpdb->term_relationships} tr_kb ON tr_kb.object_id = p.ID
1298 + INNER JOIN {$wpdb->term_taxonomy} tt_kb ON tt_kb.term_taxonomy_id = tr_kb.term_taxonomy_id AND tt_kb.taxonomy = 'knowledge_base'
1299 + INNER JOIN {$wpdb->terms} t_kb ON t_kb.term_id = tt_kb.term_id
1300 + INNER JOIN {$wpdb->term_relationships} tr_cat ON tr_cat.object_id = p.ID
1301 + INNER JOIN {$wpdb->term_taxonomy} tt_cat ON tt_cat.term_taxonomy_id = tr_cat.term_taxonomy_id AND tt_cat.taxonomy = 'doc_category'
1302 + INNER JOIN {$wpdb->terms} t_cat ON t_cat.term_id = tt_cat.term_id
1303 + WHERE p.post_name = %s AND p.post_type = 'docs'
1304 + AND t_kb.slug IN (%s, %s)
1305 + AND t_cat.slug IN (%s, %s)
1306 + LIMIT 1",
1307 + esc_sql( $name ),
1308 + esc_sql( $_kb_slug ),
1309 + esc_sql( $_kb_slug_enc ),
1310 + esc_sql( $_cat_target_enc ),
1311 + esc_sql( $_cat_target )
1312 + )
1313 + );
1314 + }
1315 +
1316 + // Fallback to the KB-only lookup (no category filter) when nothing
1317 + // matched both KB + category. Keeps single-language behaviour intact
1318 + // and lets the category-validation block below handle any genuine
1319 + // mismatch by setting invalid_request_query_vars.
1320 + if ( ! $_post_id ) {
1321 + $_post_id = (int) $wpdb->get_var(
1322 + $wpdb->prepare(
1323 + "SELECT p.ID FROM {$wpdb->posts} p
979 1324 INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
980 1325 INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'knowledge_base'
981 1326 INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
982 1327 WHERE p.post_name = %s AND p.post_type = 'docs'
@@ -981,31 +1326,91 @@
981 1326 INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
982 1327 WHERE p.post_name = %s AND p.post_type = 'docs'
983 1328 AND t.slug IN (%s, %s)
984 1329 LIMIT 1",
985 - esc_sql( $name ),
1330 + esc_sql( $_encoded_name ),
986 1331 esc_sql( $_kb_slug ),
987 1332 esc_sql( $_kb_slug_enc )
988 1333 )
989 1334 );
1335 + if ( ! $_post_id && $_encoded_name !== $name ) {
1336 + $_post_id = (int) $wpdb->get_var(
1337 + $wpdb->prepare(
1338 + "SELECT p.ID FROM {$wpdb->posts} p
1339 + INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
1340 + INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'knowledge_base'
1341 + INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
1342 + WHERE p.post_name = %s AND p.post_type = 'docs'
1343 + AND t.slug IN (%s, %s)
1344 + LIMIT 1",
1345 + esc_sql( $name ),
1346 + esc_sql( $_kb_slug ),
1347 + esc_sql( $_kb_slug_enc )
1348 + )
1349 + );
1350 + }
990 1351 }
991 1352 } else {
992 - // No KB in URL — use the simple post_name lookup (single-KB sites).
993 - $_post_id = (int) $wpdb->get_var(
1353 + // No KB in URL — disambiguate via doc_category. WPML/Polylang assign each
1354 + // translated post the same post_name (e.g. "spacious-family-home..."),
1355 + // so a plain `WHERE post_name = ... LIMIT 1` returns whichever language
1356 + // the DB serves first. When that pick does not belong to the category in
1357 + // the URL, the validation below falsely fires a 404 even though the
1358 + // correctly-translated post exists. Join doc_category so we land on the
1359 + // translation that actually owns the requested category.
1360 + $_cat_target = $target_category_slug;
1361 + $_cat_target_enc = strtolower( rawurlencode( $_cat_target ) );
1362 + $_post_id = (int) $wpdb->get_var(
994 1363 $wpdb->prepare(
995 - "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s LIMIT 1",
1364 + "SELECT p.ID FROM {$wpdb->posts} p
1365 + INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
1366 + INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'doc_category'
1367 + INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
1368 + WHERE p.post_name = %s AND p.post_type = 'docs'
1369 + AND t.slug IN (%s, %s)
1370 + LIMIT 1",
996 1371 esc_sql( $_encoded_name ),
997 - 'docs'
1372 + esc_sql( $_cat_target_enc ),
1373 + esc_sql( $_cat_target )
998 1374 )
999 1375 );
1000 1376 if ( ! $_post_id && $_encoded_name !== $name ) {
1001 1377 $_post_id = (int) $wpdb->get_var(
1002 1378 $wpdb->prepare(
1379 + "SELECT p.ID FROM {$wpdb->posts} p
1380 + INNER JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID
1381 + INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id AND tt.taxonomy = 'doc_category'
1382 + INNER JOIN {$wpdb->terms} t ON t.term_id = tt.term_id
1383 + WHERE p.post_name = %s AND p.post_type = 'docs'
1384 + AND t.slug IN (%s, %s)
1385 + LIMIT 1",
1386 + esc_sql( $name ),
1387 + esc_sql( $_cat_target_enc ),
1388 + esc_sql( $_cat_target )
1389 + )
1390 + );
1391 + }
1392 +
1393 + // Fallback: post exists with this name but not under the requested
1394 + // category. Let the category-validation block below handle the 404 so
1395 + // we keep the existing single-language behaviour intact.
1396 + if ( ! $_post_id ) {
1397 + $_post_id = (int) $wpdb->get_var(
1398 + $wpdb->prepare(
1003 1399 "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s LIMIT 1",
1004 - esc_sql( $name ),
1400 + esc_sql( $_encoded_name ),
1005 1401 'docs'
1006 1402 )
1007 1403 );
1404 + if ( ! $_post_id && $_encoded_name !== $name ) {
1405 + $_post_id = (int) $wpdb->get_var(
1406 + $wpdb->prepare(
1407 + "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = %s LIMIT 1",
1408 + esc_sql( $name ),
1409 + 'docs'
1410 + )
1411 + );
1412 + }
1008 1413 }
1009 1414 }
1010 1415
1011 1416 // If post exists, validate it belongs to the category in the URL
@@ -1160,17 +1565,23 @@
1160 1565 array_unshift( $hierarchy_path, $current_term->slug );
1161 1566 $current_term = $current_term->parent ? get_term( $current_term->parent, 'doc_category' ) : null;
1162 1567 }
1163 1568
1164 - // Check if this hierarchy matches the URL structure
1569 + // Check if this hierarchy matches the URL structure.
1570 + // WordPress/Polylang store non-Latin term slugs URL-encoded
1571 + // (%e0%a6...) while $doc_category arrives decoded from
1572 + // is_perma_valid_for. Compare in the decoded form so Bengali,
1573 + // Arabic, CJK, etc. hierarchies actually match.
1165 1574 $built_path = implode('/', $hierarchy_path);
1575 + $built_path_norm = urldecode( $built_path );
1576 + $doc_cat_norm = urldecode( $doc_category );
1166 1577
1167 1578 // Allow partial path matching to accommodate KB-prefixed URLs or partial hierarchies.
1168 1579 // Using substr for broad PHP version compatibility (equivalent to str_ends_with).
1169 - $is_suffix = strlen($built_path) > 0 && substr($doc_category, -strlen($built_path)) === $built_path;
1170 - $is_prefix = strlen($doc_category) > 0 && substr($built_path, -strlen($doc_category)) === $doc_category;
1580 + $is_suffix = strlen( $built_path_norm ) > 0 && substr( $doc_cat_norm, -strlen( $built_path_norm ) ) === $built_path_norm;
1581 + $is_prefix = strlen( $doc_cat_norm ) > 0 && substr( $built_path_norm, -strlen( $doc_cat_norm ) ) === $doc_cat_norm;
1171 1582
1172 - if ( $built_path === $doc_category || $is_suffix || $is_prefix ) {
1583 + if ( $built_path_norm === $doc_cat_norm || $is_suffix || $is_prefix ) {
1173 1584 $found_valid_hierarchy = true;
1174 1585 break;
1175 1586 }
1176 1587 }
@@ -1260,8 +1671,9 @@
1260 1671 }
1261 1672 }
1262 1673
1263 1674 return $_post_id > 0;
1675 + // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
1264 1676 }
1265 1677
1266 1678 protected function is_docs_category( $query_vars ) {
1267 1679 $result = $this->term_exists( $query_vars, 'doc_category' );
@@ -1328,8 +1740,18 @@
1328 1740
1329 1741 public function parse( $wp ) {
1330 1742 static::$already_parsed = true;
1331 1743
1744 + // An API Reference rewrite rule already matched (/docs/api/{slug}).
1745 + // The permalink magic below re-interprets the raw path against the
1746 + // docs/category/KB structures and would hijack the request whenever a
1747 + // doc_category or knowledge_base term shares the reference's slug —
1748 + // an explicit CPT match always wins.
1749 + if ( isset( $wp->query_vars['betterdocs_api_ref'] ) ) {
1750 + return;
1751 + }
1752 +
1753 + // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- legacy public filter name, retained for back-compat with Pro/extensions.
1332 1754 $this->perma_structure = apply_filters('docs_rewrite_rules', $this->perma_structure);
1333 1755
1334 1756 $this->permalink_magic( $wp );
1335 1757 }
@@ -1359,8 +1781,15 @@
1359 1781 // Strip optional language prefix injected by Polylang/WPML (e.g. "en/", "bn/", "pt-br/")
1360 1782 // so that "bn/docs/..." matches the structure "docs/..." correctly.
1361 1783 $request_without_lang = preg_replace( '#^[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})?/#', '', $request );
1362 1784
1785 + // When WPML translates a taxonomy base slug per language (e.g. doc_tag
1786 + // "docs-tag" -> "docs-tag-bn"), the incoming URL uses the translated slug,
1787 + // but perma_structure is built from the default-language slug. Map the
1788 + // leading translated slug back to its default so the raw structures match.
1789 + // No-op on non-WPML sites and when the slug isn't translated.
1790 + $request_canonical = $this->canonicalize_translated_slug( $request_without_lang );
1791 +
1363 1792 foreach ( $this->perma_structure as $_type => $structure ) {
1364 1793 // First try the raw (possibly language-prefixed) request, then the lang-stripped variant.
1365 1794 // This ensures we still match non-multilingual sites without stripping valid slugs.
1366 1795 $_perma_vars = $this->is_perma_valid_for( $structure, $request );
@@ -1366,8 +1795,11 @@
1366 1795 $_perma_vars = $this->is_perma_valid_for( $structure, $request );
1367 1796 if ( ! $_perma_vars && $request_without_lang !== $request ) {
1368 1797 $_perma_vars = $this->is_perma_valid_for( $structure, $request_without_lang );
1369 1798 }
1799 + if ( ! $_perma_vars && $request_canonical !== $request_without_lang ) {
1800 + $_perma_vars = $this->is_perma_valid_for( $structure, $request_canonical );
1801 + }
1370 1802
1371 1803 // $_valid = empty( $_valid ) && $_perma_vars ? [ 'type' => $_type, 'query_vars' => $_perma_vars ] : $_valid;
1372 1804 if ( ( $_perma_vars && method_exists( $this, $_type ) && call_user_func_array( [$this, $_type], [ & $_perma_vars] ) ) ) {
1373 1805
@@ -1415,8 +1847,46 @@
1415 1847 unset( $wp->query_vars['attachment'] );
1416 1848 }
1417 1849 }
1418 1850 }
1851 +
1852 + /**
1853 + * Map a leading WPML-translated taxonomy base slug back to its default-language
1854 + * value so the default-language perma_structure patterns can match a translated URL.
1855 + *
1856 + * Only the first path segment is considered (the taxonomy base). Returns the
1857 + * request unchanged when WPML is inactive or the leading segment isn't a
1858 + * translated BetterDocs slug.
1859 + *
1860 + * @param string $request Language-stripped request path (no leading/trailing slash).
1861 + * @return string
1862 + */
1863 + private function canonicalize_translated_slug( $request ) {
1864 + if ( $request === '' || strpos( $request, '/' ) === false ) {
1865 + return $request;
1866 + }
1867 +
1868 + $slug_map = [
1869 + 'doc_tag' => trim( $this->settings->get( 'tag_slug', 'docs-tag' ), '/' ),
1870 + 'doc_category' => trim( $this->settings->get( 'category_slug', 'docs-category' ), '/' ),
1871 + ];
1872 +
1873 + $segments = explode( '/', $request );
1874 +
1875 + foreach ( $slug_map as $taxonomy => $default ) {
1876 + if ( $default === '' ) {
1877 + continue;
1878 + }
1879 +
1880 + $translated = Helper::wpml_translated_tax_slug( $taxonomy, $default );
1881 + if ( $translated !== $default && $segments[0] === $translated ) {
1882 + $segments[0] = $default;
1883 + return implode( '/', $segments );
1884 + }
1885 + }
1886 +
1887 + return $request;
1888 + }
1419 1889
1420 1890 /**
1421 1891 * This method is responsible for checking a structure is valid again a request.
1422 1892 *