When you use WordPress plugins, you can add new functions to your website. But every plugin makes your website a bit slower. Instead of using plugins, you can use one plugin in combination with code snippets. This will keep your website fast and give you a nice overview of all the functionalities you add.

In this blog post, I want to share the best code snippets you can use for your blog website.

PHP Code Snippets

Redirect Non-Users To Other Page

add_action('template_redirect', 'redirect_non_logged_in_users');

function redirect_non_logged_in_users() {
    // Check if the user is not logged in and is not accessing wp-login.php or wp-admin
    if (!is_user_logged_in() && !is_page('wp-login.php') && !is_admin()) {
        // Redirect to the specified external URL
        wp_redirect('https://magenta-gnu-130148.hostingersite.com');
        exit;
    }
}

59 Responses

  1. As a developer, I’ve been an avid follower of Ferdy since 2018. ???? Every single video brings fresh insights and new techniques that elevate my skills! ???? Your content is a constant source of inspiration, and I truly appreciate all that you do! ????

    1. Yasir, thank you so much – since 2018! That means you’ve been here almost from the very beginning ???? It’s long-time supporters like you that keep me motivated to keep improving. Really appreciate it! ????

    1. That is not what should happen. Thanks for letting me know. You could adjust the code so that images will be compressed even better.

  2. fedy bhai ,wo kha gya code snippet webp wala jo apne video me bataya tha ???

    where’s that code snippet for converting all the images to webP?????/

    1. Hi Robin! The webP snippet was removed as it can cause compatibility issues with certain servers. Instead, use Imagify, ShortPixel, or Smush – they handle webP conversion automatically and are much more reliable! ????

    1. Hi Dave! Try the updated version Jennifer shared in the comments above – it includes extra checks that make it work reliably. Many people have confirmed it works! ????

  3. Hi,

    the code snippet doesn’t work + it’s also not the same code as you use in your youtube video; “How to make a wordpress website 2025”..

    Can you help me out?
    Thanks!

    1. Hi, I noticed the code involves comments to explain it. The problem is when you copy it and paste it , the actual code may be commented out by accident as well. These comments are shown by foward slashes, so remove them with all the slashes and be left with the code only.

      1. Great tip, Prosper! Thank you for helping out the community – that’s exactly what these comment sections are for! ????

      2. Great tip, Prosper! Thank you for helping out the community – that’s exactly what these comment sections are for! ????

    2. try this one:

      add_action(‘template_redirect’, ‘redirect_non_logged_in_users’);

      function redirect_non_logged_in_users() {

      // Allow login, admin, AJAX, and REST requests
      if (
      is_user_logged_in() ||
      is_admin() ||
      wp_doing_ajax() ||
      (defined(‘REST_REQUEST’) && REST_REQUEST)
      ) {
      return;
      }

      // Allow access to wp-login.php
      global $pagenow;
      if ($pagenow === ‘wp-login.php’) {
      return;
      }

      // Prevent redirect loop (important)
      if (strpos($_SERVER[‘REQUEST_URI’], ‘landingPage’) !== false) {
      return;
      }

      // Redirect non-logged users
      wp_redirect(‘PASTE HERE URL’);
      exit;
      }

    3. Hi Ilia! You’re right – the code in the video and on the page can differ due to updates. For the most reliable version, check the updated snippets that Jennifer and RAFAEL shared in the comments – they include proper checks for REST requests, AJAX, and the login page. Many people have confirmed those work. Hope that helps!

  4. Some people comment that the redirect non-user code doesn’t work. Here’s what I used with the plugin and it works:

    add_action(‘template_redirect’, function () {
    // Don’t redirect if user is logged in
    if (is_user_logged_in()) {
    return;
    }

    // Prevent redirect on login page, admin, or REST/API calls
    if (is_admin() || defined(‘DOING_AJAX’) || defined(‘REST_REQUEST’) || is_login()) {
    return;
    }

    // Set the external redirect URL
    $redirect_url = ‘https://puppseas.kit.com/301e8b38df’;

    // Perform redirect
    wp_redirect($redirect_url);
    exit;
    });

    1. Hey,

      Its not working for me. Any other advice? It just keeps asking me to log back in to my wordpress account and then it doesnt show me the form.

      1. Hi! If it keeps asking to log in, the redirect is working but the session isn’t sticking. Make sure you’re logging in via yoursite.com/wp-admin. Also check the snippet isn’t redirecting the login page itself – Jennifer’s version above includes is_login() to prevent exactly that. Hope it helps! ????

    2. The snippet is not working, nor is the one done by Jennifer. I was using the information from your How to make a wordpress website youtube video. Please can you respond.

    3. Jennifer, this is amazing – thank you so much for helping out the community! ???? You’re a star. I’m going to update the snippet on the page to reflect this working version.

    1. Hi Brandon! Sorry it didn’t work. Try the updated version Jennifer or RAFAEL shared – they include proper checks for REST requests, AJAX, and the login page which are the most common reasons the snippet fails. Many have confirmed those versions work! ????

    1. Hi Nicole! Sorry dat het niet werkt. Probeer de code die Jennifer of RAFAEL in de reacties hebben gedeeld – die versies werken voor veel mensen wel. De originele code had beperkingen die in de bijgewerkte versies zijn opgelost. Succes! ????

  5. Use the below code instead:

    add_action(‘template_redirect’, function () {
    // Don’t redirect if user is logged in
    if (is_user_logged_in()) {
    return;
    }

    // Allow access to admin dashboard
    if (is_admin()) {
    return;
    }

    // Allow AJAX and REST API requests
    if (defined(‘DOING_AJAX’) || defined(‘REST_REQUEST’)) {
    return;
    }

    // Allow access to login, register, lost password pages
    $current_url = $_SERVER[‘REQUEST_URI’];
    if (
    strpos($current_url, ‘wp-login.php’) !== false ||
    strpos($current_url, ‘wp-register.php’) !== false ||
    strpos($current_url, ‘lostpassword’) !== false
    ) {
    return;
    }

    // Allow known search engine bots to crawl (SEO-friendly)
    $user_agent = $_SERVER[‘HTTP_USER_AGENT’] ?? ”;
    if (preg_match(‘/Googlebot|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Sogou|Exabot|facebot|ia_archiver/i’, $user_agent)) {
    return;
    }

    // Set the external redirect URL
    $redirect_url = ‘https://equitas.sg/’;

    // Redirect and stop execution
    wp_redirect($redirect_url, 301); // 301 for SEO-friendly permanent redirect
    exit;
    });

    1. Thanks for sharing this Ankit! Especially the part about allowing search engine bots to crawl – that’s an important SEO detail the original snippet was missing. Really helpful for the community! ????

    2. Thanks for sharing this Ankit! Especially the part about allowing search engine bots to crawl – that’s an important SEO detail the original snippet was missing. Really helpful for the community! ????

  6. The Redirect Non-Users To Other Page snippet just needs a colon at the end after the the last closing curly brace.

    add_action(‘template_redirect’, ‘redirect_non_logged_in_users’);

    function redirect_non_logged_in_users() {
    // Check if the user is not logged in and is not accessing wp-login.php or wp-admin
    if (!is_user_logged_in() && !is_page(‘wp-login.php’) && !is_admin()) {
    // Redirect to the specified external URL
    wp_redirect(‘https://magenta-gnu-130148.hostingersite.com’);
    exit;
    }
    };

    1. Hi Tim! The webP snippet was removed as it can cause issues on certain servers. Instead I recommend a plugin like Imagify, ShortPixel, or Smush – they handle webP conversion automatically and are much more reliable than a custom snippet. ????

    2. Hi Tim! The webP snippet was removed as it can cause issues on certain servers. Instead use a plugin like Imagify, ShortPixel, or Smush – they handle webP conversion automatically and are much more reliable. ????

  7. Hi Ferdy

    I tried your code snippet for Redirect Non-Users To Other Page as you suggested in your YouTube video. I followed all your instructions, but it is not working. I’m trying to build my website, but it is showing live, which I don’t really want.
    Your help would be greatly appreciated.
    Thanks

      1. Hi Maya! Sorry you’re still having trouble. Try the updated code that RAFAEL shared above – it includes proper checks for REST requests and the login page which are usually the culprit. Also make sure you’re adding it via the WP Code plugin with PHP as the code type. Good luck! ????

      2. Hi Maya! Sorry you’re still having trouble. Try the updated code RAFAEL shared above – it includes proper checks for REST requests and the login page. Also make sure you’re adding it via the WP Code plugin with PHP as the code type. Good luck! ????

    1. Hi Lina! Sorry to hear that. A few things to check: 1) Make sure you’re using the WP Code plugin to add the snippet, 2) Replace ‘PASTE HERE URL’ with your actual URL, 3) Try the updated version Jennifer or RAFAEL shared in the comments – those have been confirmed to work by many users. Good luck! ????

    2. Hi Lina! A few things to check: 1) Use the WP Code plugin to add the snippet, 2) Replace ‘PASTE HERE URL’ with your actual URL, 3) Try the updated version Jennifer or RAFAEL shared in the comments – those have been confirmed to work. Good luck! ????

  8. Hey Just working my way through your Divi 5 Video. This code snippet is different from the one that you show in the tutorial and is not working. I just thought You would like to know because you have put so much hard work into your tutorial and it just dropped a couple of weeks ago. Thanks for your hard work.

    1. Hi Charles! You’re right, and I appreciate you pointing that out. The snippet on the page and the one in the video can sometimes differ due to updates. The community has been amazing though – Jennifer and RAFAEL have both shared updated working versions in the comments that many people have confirmed work. Give those a try! ????

    2. Hi Charles! You’re right – the snippet on the page and video can differ due to updates. Jennifer and RAFAEL have both shared updated working versions in the comments that many people confirmed work. Give those a try! ????

  9. That small contrast between “one more plugin” and “a nice overview” is what stayed with me. You’re not only chasing speed there, you’re protecting clarity, which makes the whole approach feel calmer and more intentional.

  10. This code works for your video example using a hostinger hosted account. I had Kodee rewrite it and it worked for me. Good luck WP tutorial users.

    ======

    add_action(‘template_redirect’, ‘redirect_non_logged_in_users’);

    function redirect_non_logged_in_users() {
    if (
    is_user_logged_in() ||
    is_admin() ||
    wp_doing_ajax() ||
    (defined(‘REST_REQUEST’) && REST_REQUEST)
    ) {
    return;
    }

    global $pagenow;
    if ($pagenow === ‘wp-login.php’) {
    return;
    }

    if (isset($_SERVER[‘REQUEST_URI’]) && strpos($_SERVER[‘REQUEST_URI’], ‘landingPage’) !== false) {
    return;
    }

    wp_redirect(‘https://omniform1.com/forms/v1/landingPage/6a0f49b4d38720b69441e087/6a0f4bd320c44ebafb3756ff’);
    exit;
    }

    =====
    Cheers,

    Mystr B

  11. I really like your blog.. very nice colors & theme.
    Did you create this website yourself or did you hire someone to do it for you?
    Plz respond as I’m looking to create my own blog and would like to
    know where u got this from. thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *