<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Andrew Lazarev</title>
    <description>The latest articles on DEV Community by Andrew Lazarev (@andrewinsidelazarev).</description>
    <link>https://dev.to/andrewinsidelazarev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1039174%2F5c086640-3511-4a1c-b913-89372c5f01aa.png</url>
      <title>DEV Community: Andrew Lazarev</title>
      <link>https://dev.to/andrewinsidelazarev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/andrewinsidelazarev"/>
    <language>en</language>
    <item>
      <title>Advanced 404-page snippet for WordPress</title>
      <dc:creator>Andrew Lazarev</dc:creator>
      <pubDate>Sun, 24 Nov 2024 21:09:29 +0000</pubDate>
      <link>https://dev.to/andrewinsidelazarev/advanced-404-page-snippet-for-wordpress-39me</link>
      <guid>https://dev.to/andrewinsidelazarev/advanced-404-page-snippet-for-wordpress-39me</guid>
      <description>&lt;p&gt;This PHP code is designed to handle custom 404 errors in a WordPress environment. Its main purpose is to improve the user experience by attempting to redirect users to the most relevant page or provide helpful suggestions if a requested URL cannot be found. Here's a detailed breakdown of what the code does:&lt;/p&gt;

&lt;p&gt;Key Features:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.&lt;/strong&gt; Extract the Last Segment of the URL:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The script retrieves the requested URL and isolates the last part of the path (e.g., for /some/path/example, it extracts example).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2.&lt;/strong&gt; Search for Existing Paths:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A function (find_existing_path) is used to check whether the extracted segment matches:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;-- A published post slug.&lt;br&gt;
   -- A tag slug in the WordPress taxonomy.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a match is found, the function returns the URL of the corresponding post or tag.&lt;/li&gt;
&lt;li&gt;If no match is found in the primary database search, it checks a predefined list of folders (blog, category, etc.) for potential matches. If a match exists, it constructs and returns the appropriate URL.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;3.&lt;/strong&gt; Redirect to the Found Path:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If a matching path is found in the search process, the user is redirected to it using a 301 permanent redirect.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;4.&lt;/strong&gt; Search for Similar Content:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If no exact match is found, the script converts the last segment into a search query by replacing special characters (-, _, and %20) with +.&lt;/li&gt;
&lt;li&gt;It performs a WordPress search query to find up to 5 posts that might be relevant.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;5.&lt;/strong&gt; Display Search Results:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If matching posts are found, it displays them to the user in the following way:
-- A heading is shown in the appropriate language (Russian, Italian, or English), depending on the site's locale.
-- Instead of plain links, the thumbnails of the suggested posts are displayed using a loop (get_template_part).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;6.&lt;/strong&gt; Fallback:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If neither a matching path nor search results are found, the standard 404 error page will remain.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Purpose:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This script enhances WordPress’s default 404 error handling by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Redirecting users to relevant pages if possible.&lt;/li&gt;
&lt;li&gt;Providing search-based suggestions when exact matches are unavailable.&lt;/li&gt;
&lt;li&gt;Improving user navigation and potentially reducing bounce rates.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;`&lt;br&gt;
function handle_custom_404() {&lt;br&gt;
    // Get the requested URL path&lt;br&gt;
    $request_uri = $_SERVER['REQUEST_URI'];&lt;br&gt;
    $request_path = trim(urldecode($request_uri), '/');&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Extract only the last segment of the path
$last_segment = basename($request_path);

// Function to search for an existing path in other folders
function find_existing_path($path) {
    global $wpdb;

    // Perform a combined query to search for slugs in posts and tags without a LIMIT 1 restriction
    $results = $wpdb-&amp;gt;get_results($wpdb-&amp;gt;prepare(
        "(SELECT ID AS item_id, 'post' AS item_type FROM {$wpdb-&amp;gt;posts} 
          WHERE post_name = %s AND post_status = 'publish')
        UNION ALL
        (SELECT t.term_id AS item_id, 'tag' AS item_type FROM {$wpdb-&amp;gt;terms} t
          INNER JOIN {$wpdb-&amp;gt;term_taxonomy} tt ON t.term_id = tt.term_id
          WHERE t.slug = %s AND tt.taxonomy = 'post_tag')",
        $path, $path
    ));

    // If exactly one record is found, return its URL
    if (count($results) === 1) {
        $result = $results[0];
        if ($result-&amp;gt;item_type === 'post') {
            return get_permalink($result-&amp;gt;item_id);
        } elseif ($result-&amp;gt;item_type === 'tag') {
            return get_tag_link($result-&amp;gt;item_id);
        }
    }

    // If multiple results or none are found, use the old logic
    $paths_to_check = ['blog', 'category', 'news', 'tag', 'news/news-photo'];

    foreach ($paths_to_check as $folder) {
        $potential_path = $folder . '/' . $path;

        // Check if a page exists at this path or a term exists in the required taxonomy
        if (url_to_postid(site_url($potential_path)) != 0 || term_exists($path, $folder)) {
            return site_url($potential_path);
        }
    }

    return false;
}

// Check if a similar path exists in other folders
$existing_path = find_existing_path($last_segment);

if ($existing_path) {
    // If a similar path is found, perform a redirect
    wp_redirect($existing_path, 301);
    exit;
}

// Search by keywords, replacing "-" and "_" with pluses
$search_query = str_replace(['-', '_', '%20'], '+', $last_segment);

// Perform a search by keywords
$search = new WP_Query([
    's' =&amp;gt; $search_query,
    'posts_per_page' =&amp;gt; 5
]);

// Output results if found
if ($search-&amp;gt;have_posts()) {
    echo '&amp;lt;/br&amp;gt;';

    $locale = get_locale();
    if ($locale === 'ru_RU') {
        echo '&amp;lt;h2&amp;gt;Возможно Вы искали это:&amp;lt;/h2&amp;gt;';
    } elseif ($locale === 'it_IT') {
        echo '&amp;lt;h2&amp;gt;Forse stavi cercando questo:&amp;lt;/h2&amp;gt;';
    } else {
        echo '&amp;lt;h2&amp;gt;Perhaps you were looking for this:&amp;lt;/h2&amp;gt;';
    }
    echo '&amp;lt;/br&amp;gt;';
    echo '&amp;lt;div&amp;gt;';
    // Instead of displaying links, output post thumbnails
    while ($search-&amp;gt;have_posts()) : 
        $search-&amp;gt;the_post();
        echo '&amp;lt;div class="post-thumbnail"&amp;gt;';
        get_template_part('content', get_post_format());
        echo '&amp;lt;/div&amp;gt;';
    endwhile;

    // Output pagination
    // the_posts_pagination();

    echo '&amp;lt;/div&amp;gt;';
    wp_reset_postdata();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;`&lt;/p&gt;

&lt;p&gt;This code &lt;a href="https://gist.github.com/andrewinsidelazarev/a154843e447333fd2247585d74c9cea3" rel="noopener noreferrer"&gt;on GitHub&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://andrew-lazarev.com/en/contacts-en/" rel="noopener noreferrer"&gt;Contact with me&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
