mbis

Wildcard redirect

Sep 1st, 2025
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.30 KB | None | 0 0
  1. /**
  2.  * Automatically redirect to the canonical URL if slug extracted from URL matches a CPT item and 404 error is expected
  3.  */
  4. function bis_guess_cpt_url() {
  5.     global $wpdb, $wp;
  6.  
  7.     if ( is_404() && ! empty( $wp->request ) ) {
  8.         // Define the URL bases that should trigger the redirect & custom post types
  9.         $url_bases = array( 'document', 'custom-base' );
  10.         $post_types = array( 'product', 'custom_post_type1', 'custom_post_type2' );
  11.  
  12.         // Check if the request starts with one of the allowed bases
  13.         $matches_base = false;
  14.         foreach ( $url_bases as $base ) {
  15.             if ( strpos( $wp->request, $base ) === 0 ) {
  16.                 $matches_base = true;
  17.                 break;
  18.             }
  19.         }
  20.  
  21.         if ( ! $matches_base ) {
  22.             return;
  23.         }
  24.  
  25.         // Extract the last part of the URL path as the slug
  26.         $slug = basename( $wp->request );
  27.  
  28.         foreach ( $post_types as $post_type ) {
  29.             $where = $wpdb->prepare( 'post_name = %s AND post_type = %s AND post_status = %s', $slug, $post_type, 'publish' );
  30.             $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where LIMIT 1" );
  31.  
  32.             if ( ! empty( $post_id ) ) {
  33.                 $permalink = get_permalink( (int) $post_id );
  34.                 if ( ! empty( $permalink ) ) {
  35.                     wp_safe_redirect( $permalink, 301, 'Bis' );
  36.                     exit();
  37.                 }
  38.             }
  39.         }
  40.     }
  41. }
  42. add_action( 'template_redirect', 'bis_guess_cpt_url' );
Advertisement
Add Comment
Please, Sign In to add comment