4,9 based on 300 reviews
Trusted by 1500+ businesses and student of all shapes and sizes
4,9 based on 300 reviews
Trusted by 1500+ businesses and student of all shapes and sizes
WordPress code snippets tutorial

The Best Code Snippets For WordPress

Code Snippets

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://ferdy.com');
        exit;
    }
}

58 thoughts on “The Best Code Snippets For WordPress”

  • 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! ????

    • A

      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! ????

  • Shar Ali

    Amazing helping support for the developer. Very easy way from you. Thanks Ferdy.

    • A

      Thank you, Shar Ali! ???? Happy it was helpful for your work. Keep building great things! ????

  • I tried the jpg convert to webp and my file sizes actually went higher and some almost doubled my file size.

    • A

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

  • Robin Sharma

    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?????/

    • A

      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! ????

  • the code snippet doesn’t work for me?

    • A

      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! ????

  • ilia corthout

    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!

    • Prosper

      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.

      • Nova Bot

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

      • A

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

    • 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;
      }

    • A

      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!

  • 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;
    });

    • 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.

      • A

        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! ????

    • 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.

    • A

      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.

  • NOPE the redirect link did not work for me either

    • A

      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! ????

  • De code werkt niet Ferdy? ik heb alle stappen gevolgd van je video, maar helaas het werkt echt niet

    • A

      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! ????

  • Very easy way. Thank You .

  • 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;
    });

    • Nova Bot

      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! ????

    • A

      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! ????

  • 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://ferdy.com’);
    exit;
    }
    };

    • Nova Bot

      Thanks Chris! Great of you to share the fix with the community – really helpful! ????

  • Where is the “convert to webP” snippet from you video – https://www.youtube.com/watch?v=K7P0W_kXkd8&t=257s

    • Nova Bot

      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. ????

    • A

      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. ????

  • 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

  • Hi Ferdy
    Ignore my previous comment as it appears to be working correctly now. Thank you for all your help.

    • Maya Hugenholtz

      What did you do to get it working. Still not working for me

      • Nova Bot

        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! ????

      • A

        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! ????

  • Nice one! I was looking for this one.

    • Nova Bot

      Happy you found it Robert! ???? Hope it serves you well!

  • I am learning to build a webpage and the snippet is not working.

    • Nova Bot

      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! ????

    • A

      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! ????

  • 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.

    • Nova Bot

      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! ????

    • A

      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! ????

  • 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.

  • 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

  • Hey!
    I’m really happy with the turorial; very easy to follow. However, this code is not working. I just end up with a search form. How do I figure out the problem?

  • A

    Hi Javier! Try the snippet Jennifer shared above – she’s added is_login() and a few other checks that make it work properly. Worked for a lot of people! ????

  • A

    Hi Luwam! That sounds like you might have some caching going on. Try clearing your site cache and browser cache after applying the snippet. If you’re using a caching plugin, exclude the redirect pages from cache. Hope that helps! ????

  • A

    Hi Lydia! To troubleshoot: 1) Make sure WP Code is active, 2) Check the snippet is ‘Active’ in WP Code, 3) Try Jennifer’s updated version in the comments, 4) Clear your cache. Most issues are fixed by one of those. Good luck! ????

  • A

    Hi Sarra! This usually happens when WordPress doesn’t recognise the request type and the redirect fires on every page including admin. Make sure you’re using Jennifer’s updated version from the comments – it includes is_admin() checks that prevent this. ????

  • A

    Hi Ali! Try Jennifer’s updated snippet from the comments above – it includes all the right exclusions. Also make sure you’re not logged in as admin when testing (use a private/incognito window). Good luck! ????

  • A

    Hi Alexis! Yes, try Jennifer’s updated snippet from the comments – it includes better handling for AJAX and REST requests which are the most common cause of redirect loops. Good luck! ????

  • A

    Hi Patrick! Try Jennifer’s updated version in the comments – it resolves most redirect issues including admin loops. Also clear your cache after applying. Hope that fixes it! ????

Leave your comment

Build stunning websites with Elementor
Hostinger web hosting with real power

MORE BLOGS