We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 10405
    • 288 Posts
    I’m trying to customise the functionality of the MODx default 404 page so that it queries a database (separate to the MODx db) and chooses whether to redirect to a URL or show the default 404 page based on the contents of the db.

    The database I’ve set up is very simple with a field that will represent a forwarding URL. The 404 needs to look at the db whilst loading, and then one of things should happen:

    If the user-mistyped URL (which would normally just bring up the 404 page) matches a record in the db, we don’t display the 404 page- instead we somehow need to redirect the user to a specific (internal) URL.

    If however the typed URL doesn’t match a record in the db then we just display the 404 as normal.

    Is this possible with the MODx 404 page and if so, does anyone know how this can be achieved?

    Many thanks
      • 10405
      • 288 Posts
      Does anyone know if this can be done at all?
        • 3749
        • 24,544 Posts
        Yes, definitely. What you want is a custom plugin that listens to the MODx onPageNotFound system event.

        Here’s an example that sends the user to a different page based on the time of day:

        <?php
        
        /* Page Not Found Plugin */
        
        $busStart = 9;
        $busEnd = 16;
        
        $dayPage = 5;  /* id of page to use during business hours */
        $nightPage = 38; /* id of page to use during non-business hours */
        
        $busStartSecs = $busStart * 3600;
        $busEndSecs = $busEnd * 3600;
        
        $secsSinceMidnight = (date("G") * 3600) + (date("i") * 60) + date("s");
        
        if ($secsSinceMidnight >= $busStartSecs && $secsSinceMidnight <= $busEndSecs) {
            $modx->sendForward($dayPage);
        } else {
            $modx->sendForward($nightPage);
        }
        ?>
          Did I help you? Buy me a beer
          Get my Book: MODX:The Official Guide
          MODX info for everyone: http://bobsguides.com/modx.html
          My MODX Extras
          Bob's Guides is now hosted at A2 MODX Hosting