75+ Must‑Have WordPress Cheat Sheet and Code Snippets


Let’s be honest – WordPress development can feel overwhelming sometimes. Whether you’re a seasoned developer juggling multiple projects or someone just getting their feet wet, there’s always that moment when you think, “I know I’ve done this before, but what was that exact code snippet again?”

Sound familiar? You’re definitely not alone.

As you can see, Hostinger offers a lot of benefits for website owners. With affordable pricing, top-notch performance, and advanced security features, they are a fantastic choice for hosting your website.

That’s exactly why I’ve put together this comprehensive WordPress cheat sheet. Think of it as your trusty sidekick that’ll save you countless hours of Googling and Stack Overflow diving. We’re covering everything from basic PHP functions to advanced customizations that’ll make your WordPress sites shine.

Why Every WordPress Developer Needs a Reliable Cheat Sheet

Before we dive into the good stuff, let’s talk about why having a go-to reference is a game-changer. WordPress powers over 40% of all websites on the internet, which means there’s an incredible demand for developers who can work efficiently with the platform.

The thing is, WordPress has evolved significantly over the years. With new features, functions, and best practices constantly emerging, even experienced developers can’t remember every single code snippet or function parameter. That’s where this cheat sheet comes in handy.

(Ad)
Publish Your Guest Post at SmashingApps.com and Grow Your Business with Us

WordPress Cheat Sheet and Code Snippets

Essential WordPress Functions and Hooks

Let’s start with the bread and butter of WordPress development – the functions and hooks you’ll use almost daily.

The Most Common WordPress Functions

Getting WordPress URLs:

// Home URL
echo home_url();

// Site URL  
echo site_url();

// Admin URL
echo admin_url();

// Current page URL
echo get_permalink();

// Theme directory URL
echo get_template_directory_uri();

Working with Posts and Pages:

// Get post/page content
echo get_the_content();

// Get post excerpt
echo get_the_excerpt();

// Get post title
echo get_the_title();

// Get post date
echo get_the_date();

// Check if we're on a single post
if (is_single()) {
    // Your code here
}

// Check if we're on a page
if (is_page()) {
    // Your code here
}

Essential Action Hooks

Action hooks are your best friends when you want to add functionality at specific points in WordPress execution.

// Add scripts and styles
add_action('wp_enqueue_scripts', 'your_function_name');

// Initialize functionality
add_action('init', 'your_init_function');

// Run code after theme setup
add_action('after_setup_theme', 'your_setup_function');

// Add admin scripts
add_action('admin_enqueue_scripts', 'your_admin_scripts');

// Custom post type registration
add_action('init', 'register_custom_post_type');

Filter Hooks You’ll Actually Use

Filters let you modify data before it’s displayed or processed.

// Modify the main query
add_filter('pre_get_posts', 'modify_main_query');

// Change excerpt length
add_filter('excerpt_length', 'custom_excerpt_length');

// Modify post content
add_filter('the_content', 'add_custom_content');

// Change login logo
add_filter('login_headerurl', 'custom_login_logo_url');

Theme Development Essentials

Creating custom themes is where WordPress development gets really exciting. Here are the snippets you’ll reach for again and again.

You can click here to check out 100s of responsive wordpress themes to design your responsive website.

Theme Setup Functions

Every good theme starts with proper setup. Here’s what should go in your functions.php:

function theme_setup() {
    // Add theme support for post thumbnails
    add_theme_support('post-thumbnails');
    
    // Add theme support for title tag
    add_theme_support('title-tag');
    
    // Add theme support for custom logo
    add_theme_support('custom-logo');
    
    // Add theme support for HTML5
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // Register navigation menus
    register_nav_menus(array(
        'primary' => 'Primary Menu',
        'footer' => 'Footer Menu',
    ));
}
add_action('after_setup_theme', 'theme_setup');

Enqueuing Scripts and Styles Properly

Click here to read  How to Create an Apple ID: A Step-by-Step Guide for All Levels

One of the biggest mistakes I see developers make is loading scripts and styles incorrectly. Here’s the right way:

function enqueue_theme_assets() {
    // Enqueue main stylesheet
    wp_enqueue_style('theme-style', get_stylesheet_uri());
    
    // Enqueue custom CSS
    wp_enqueue_style('custom-style', get_template_directory_uri() . '/css/custom.css');
    
    // Enqueue jQuery (if not already loaded)
    wp_enqueue_script('jquery');
    
    // Enqueue custom JavaScript
    wp_enqueue_script('theme-script', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);
    
    // Localize script for AJAX
    wp_localize_script('theme-script', 'ajax_object', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('ajax_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_theme_assets');

Creating Custom Page Templates

Sometimes you need pages that look completely different from your standard template. Here’s how to create them:

<?php
/*
Template Name: Custom Landing Page
*/

get_header(); ?>

<div class="custom-landing-page">
    <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>
            <h1><?php the_title(); ?></h1>
            <div class="content">
                <?php the_content(); ?>
            </div>
        <?php endwhile; ?>
    <?php endif; ?>
</div>

<?php get_footer(); ?>

Working with Custom Fields and Meta Data

Custom fields are incredibly powerful for creating dynamic, content-rich websites. Here’s how to work with them effectively.

Let’s break it down difference between WP Super Cache and LiteSpeed Cache in simple terms, figure out which one’s better for your site, and learn how to supercharge your website using LiteSpeed Cache on Hostinger.

Adding and Retrieving Custom Fields

// Add custom meta box
function add_custom_meta_box() {
    add_meta_box(
        'custom-meta-box',
        'Custom Fields',
        'custom_meta_box_callback',
        'post'
    );
}
add_action('add_meta_boxes', 'add_custom_meta_box');

// Meta box callback
function custom_meta_box_callback($post) {
    wp_nonce_field('save_custom_meta', 'custom_meta_nonce');
    $value = get_post_meta($post->ID, '_custom_field', true);
    echo '<input type="text" name="custom_field" value="' . esc_attr($value) . '" />';
}

// Save custom field
function save_custom_meta($post_id) {
    if (!wp_verify_nonce($_POST['custom_meta_nonce'], 'save_custom_meta')) {
        return;
    }
    
    if (isset($_POST['custom_field'])) {
        update_post_meta($post_id, '_custom_field', sanitize_text_field($_POST['custom_field']));
    }
}
add_action('save_post', 'save_custom_meta');

// Retrieve custom field in template
$custom_value = get_post_meta(get_the_ID(), '_custom_field', true);
if ($custom_value) {
    echo '<p>Custom Field: ' . esc_html($custom_value) . '</p>';
}

Custom Post Types and Taxonomies

Custom post types are essential for creating websites that go beyond basic blogging. Here’s everything you need to know.

Publication dates are your secret weapon for navigating the digital world confidently. Whether you’re vetting sources, analyzing competitors, or building your own site’s credibility, these methods ensure you’re working with accurate, up-to-date information.

Creating Custom Post Types

function register_custom_post_type() {
    $args = array(
        'public' => true,
        'label' => 'Portfolio',
        'labels' => array(
            'name' => 'Portfolio Items',
            'singular_name' => 'Portfolio Item',
            'add_new' => 'Add New Item',
            'add_new_item' => 'Add New Portfolio Item',
            'edit_item' => 'Edit Portfolio Item',
        ),
        'supports' => array('title', 'editor', 'thumbnail', 'excerpt'),
        'has_archive' => true,
        'rewrite' => array('slug' => 'portfolio'),
        'menu_icon' => 'dashicons-portfolio',
    );
    
    register_post_type('portfolio', $args);
}
add_action('init', 'register_custom_post_type');

Custom Taxonomies

function register_custom_taxonomy() {
    $args = array(
        'hierarchical' => true,
        'labels' => array(
            'name' => 'Portfolio Categories',
            'singular_name' => 'Portfolio Category',
        ),
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'portfolio-category'),
    );
    
    register_taxonomy('portfolio_category', array('portfolio'), $args);
}
add_action('init', 'register_custom_taxonomy');

WordPress Loop Variations

The WordPress Loop is fundamental to displaying content. Here are different variations you’ll need.

Click here to read  40+ Must-See Resources And Inspirational Collections For Designers To Discover The Best Of The Web In March

Basic Loop

<?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
            <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
            <div class="post-meta">
                <span>By <?php the_author(); ?> on <?php the_date(); ?></span>
            </div>
            <div class="post-content">
                <?php the_excerpt(); ?>
            </div>
        </article>
    <?php endwhile; ?>
    
    <?php the_posts_navigation(); ?>
<?php else : ?>
    <p>No posts found.</p>
<?php endif; ?>

Custom Query Loop

$custom_query = new WP_Query(array(
    'post_type' => 'portfolio',
    'posts_per_page' => 6,
    'meta_query' => array(
        array(
            'key' => 'featured',
            'value' => 'yes',
            'compare' => '='
        )
    )
));

if ($custom_query->have_posts()) :
    while ($custom_query->have_posts()) : $custom_query->the_post();
        // Your template code here
    endwhile;
    wp_reset_postdata();
endif;

User Management and Authentication

Working with users is a common requirement in WordPress development. Here are the essential snippets.

User Registration and Login

// Check if user is logged in
if (is_user_logged_in()) {
    $current_user = wp_get_current_user();
    echo 'Hello, ' . $current_user->display_name;
} else {
    echo '<a href="' . wp_login_url() . '">Login</a>';
}

// Get user meta
$user_meta = get_user_meta($user_id, 'meta_key', true);

// Update user meta
update_user_meta($user_id, 'meta_key', 'meta_value');

// Check user capabilities
if (current_user_can('edit_posts')) {
    // User can edit posts
}

Custom User Roles

// Add custom user role
function add_custom_user_role() {
    add_role(
        'custom_role',
        'Custom Role',
        array(
            'read' => true,
            'edit_posts' => false,
            'delete_posts' => false,
        )
    );
}
add_action('init', 'add_custom_user_role');

Security Best Practices

Security should never be an afterthought. Here are essential security snippets every WordPress developer should use.

Data Sanitization and Validation

// Sanitize text input
$clean_text = sanitize_text_field($_POST['user_input']);

// Sanitize email
$clean_email = sanitize_email($_POST['email']);

// Sanitize URL
$clean_url = esc_url($_POST['website']);

// Escape output
echo esc_html($user_content);
echo esc_attr($attribute_value);
echo esc_url($link_url);

// Nonce verification
if (wp_verify_nonce($_POST['nonce_field'], 'nonce_action')) {
    // Process form
}

Preventing Direct Access

// At the top of your PHP files
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

Database Operations

Sometimes you need to interact directly with the WordPress database. Here’s how to do it safely.

Using $wpdb

global $wpdb;

// Get results
$results = $wpdb->get_results(
    $wpdb->prepare(
        "SELECT * FROM {$wpdb->posts} WHERE post_status = %s AND post_type = %s",
        'publish',
        'post'
    )
);

// Insert data
$wpdb->insert(
    $wpdb->prefix . 'custom_table',
    array(
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ),
    array('%s', '%s')
);

// Update data
$wpdb->update(
    $wpdb->prefix . 'custom_table',
    array('name' => 'Jane Doe'),
    array('id' => 1),
    array('%s'),
    array('%d')
);

AJAX in WordPress

AJAX functionality can make your WordPress sites feel more dynamic and responsive.

Whether you’re a SaaS startup, e-commerce store, or local service provider, A multi language website is about connecting with global audiences on their terms.

Setting Up AJAX

// Enqueue script with localized data
function enqueue_ajax_script() {
    wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/ajax.js', array('jquery'));
    wp_localize_script('custom-ajax', 'ajax_params', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('ajax_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_script');

// AJAX handler for logged-in users
function handle_ajax_request() {
    check_ajax_referer('ajax_nonce', 'nonce');
    
    // Your AJAX logic here
    $response = array('success' => true, 'data' => 'Response data');
    
    wp_send_json($response);
}
add_action('wp_ajax_custom_action', 'handle_ajax_request');

// AJAX handler for non-logged-in users
add_action('wp_ajax_nopriv_custom_action', 'handle_ajax_request');

JavaScript Side

jQuery(document).ready(function($) {
    $('.ajax-button').click(function(e) {
        e.preventDefault();
        
        $.ajax({
            url: ajax_params.ajax_url,
            type: 'POST',
            data: {
                action: 'custom_action',
                nonce: ajax_params.nonce,
                // Additional data
            },
            success: function(response) {
                if (response.success) {
                    // Handle success
                    console.log(response.data);
                }
            },
            error: function() {
                // Handle error
            }
        });
    });
});

Customizing the WordPress Admin

Sometimes you need to customize the WordPress admin area for your clients or specific use cases.

Click here to read  How to Use LinkedIn AI Job Search Tool: Step-by-Step Guide

Elementor Pro unlocks premium widgets, forms, and templates for $59/year.

Admin Customizations

// Remove admin menu items
function remove_admin_menus() {
    remove_menu_page('edit-comments.php'); // Comments
    remove_menu_page('tools.php'); // Tools
}
add_action('admin_menu', 'remove_admin_menus');

// Add custom admin page
function add_custom_admin_page() {
    add_menu_page(
        'Custom Settings',
        'Custom Settings',
        'manage_options',
        'custom-settings',
        'custom_admin_page_callback',
        'dashicons-admin-generic',
        30
    );
}
add_action('admin_menu', 'add_custom_admin_page');

function custom_admin_page_callback() {
    echo '<div class="wrap"><h1>Custom Settings</h1><p>Your custom admin page content here.</p></div>';
}

// Custom admin styles
function custom_admin_styles() {
    echo '<style>
        .wp-admin #wpbody-content {
            padding-bottom: 65px;
        }
    </style>';
}
add_action('admin_head', 'custom_admin_styles');

Performance Optimization Snippets

Performance is crucial for user experience and SEO. Here are some snippets to help optimize your WordPress sites.

We’ll also cover troubleshooting tips for when your hostinger website not working turns into a persistent headache and provide detailed explanations on how to use WordPress on Hostinger along with installation tips.

Caching and Optimization

// Disable unnecessary features
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');

// Optimize database queries
function optimize_database_queries() {
    if (!is_admin()) {
        // Remove unnecessary queries
        remove_action('wp_head', 'wp_shortlink_wp_head');
    }
}
add_action('init', 'optimize_database_queries');

// Enable Gzip compression
function enable_gzip_compression() {
    if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
        ob_start('ob_gzhandler');
    } else {
        ob_start();
    }
}
add_action('init', 'enable_gzip_compression');

Troubleshooting Common Issues

Every WordPress developer runs into issues. Here are solutions to the most common problems.

Debug Mode Setup

// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);

// Custom error logging
function custom_error_log($message) {
    if (WP_DEBUG === true) {
        error_log(print_r($message, true));
    }
}

Memory and Execution Time

// Increase memory limit
ini_set('memory_limit', '256M');

// Increase execution time
ini_set('max_execution_time', 300);

// Check current limits
function check_system_limits() {
    echo 'Memory Limit: ' . ini_get('memory_limit') . '<br>';
    echo 'Max Execution Time: ' . ini_get('max_execution_time') . '<br>';
    echo 'WordPress Memory Limit: ' . WP_MEMORY_LIMIT . '<br>';
}

Quick Reference: Most Used Functions

Here’s a rapid-fire list of functions you’ll use constantly:

Post Functions:

  • the_title() – Display post title
  • the_content() – Display post content
  • the_excerpt() – Display post excerpt
  • the_permalink() – Display post URL
  • get_the_ID() – Get current post ID

Theme Functions:

  • get_header() – Include header template
  • get_footer() – Include footer template
  • get_sidebar() – Include sidebar template
  • get_template_part() – Include template part

URL Functions:

  • home_url() – Get home URL
  • site_url() – Get site URL
  • admin_url() – Get admin URL
  • get_template_directory_uri() – Get theme directory URL

Wrapping Up: Your WordPress Cheat Sheet and Code Snippets

There you have it – your comprehensive WordPress cheat sheet that covers everything from basic functions to advanced customizations. I’ve tried to include the snippets that I find myself reaching for repeatedly in real-world projects.

The key to becoming a more efficient WordPress developer isn’t memorizing every single function (that’s impossible anyway), but knowing where to find reliable, tested code snippets when you need them. Bookmark this guide, and don’t hesitate to refer back to it whenever you’re working on a WordPress project.

Remember, WordPress development is constantly evolving. New features, security updates, and best practices emerge regularly. While these snippets will serve you well, always stay curious and keep learning. The WordPress community is incredibly supportive, and there are always new techniques to discover.

What’s your go-to WordPress snippet that I might have missed? Every developer has those favorite pieces of code that make their workflow smoother. Feel free to share your essential snippets – we’re all in this together, making the web a better place one WordPress site at a time.