Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Automatically redirect to the canonical URL if slug extracted from URL matches a CPT item and 404 error is expected
- */
- function bis_guess_cpt_url() {
- global $wpdb, $wp;
- if ( is_404() && ! empty( $wp->request ) ) {
- // Define the URL bases that should trigger the redirect & custom post types
- $url_bases = array( 'document', 'custom-base' );
- $post_types = array( 'product', 'custom_post_type1', 'custom_post_type2' );
- // Check if the request starts with one of the allowed bases
- $matches_base = false;
- foreach ( $url_bases as $base ) {
- if ( strpos( $wp->request, $base ) === 0 ) {
- $matches_base = true;
- break;
- }
- }
- if ( ! $matches_base ) {
- return;
- }
- // Extract the last part of the URL path as the slug
- $slug = basename( $wp->request );
- foreach ( $post_types as $post_type ) {
- $where = $wpdb->prepare( 'post_name = %s AND post_type = %s AND post_status = %s', $slug, $post_type, 'publish' );
- $post_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE $where LIMIT 1" );
- if ( ! empty( $post_id ) ) {
- $permalink = get_permalink( (int) $post_id );
- if ( ! empty( $permalink ) ) {
- wp_safe_redirect( $permalink, 301, 'Bis' );
- exit();
- }
- }
- }
- }
- }
- add_action( 'template_redirect', 'bis_guess_cpt_url' );
Advertisement
Add Comment
Please, Sign In to add comment