A curated collection of 225+ battle-tested WordPress code snippets, best practices, and cheat sheets for developers. Stop Googling the same things β everything you need in one place.
- 225+ ready-to-use snippets covering every aspect of WordPress development
- Organised by category β find what you need in seconds
- Covers modern WordPress: Gutenberg, REST API, Full Site Editing
- Each snippet is tested, documented, and production-ready
- Updated regularly with new snippets from the community
- πͺ Hooks (Actions & Filters)
- π WP_Query & Database
- π Security
- β‘ Performance
- π§± Gutenberg & Block Editor
- π AJAX
- π REST API
- π¨ Theme Development
- π Plugin Development
- π€ Contributing
add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
function my_theme_scripts(): void {
wp_enqueue_style(
'my-style',
get_template_directory_uri() . '/css/style.css',
[],
filemtime( get_template_directory() . '/css/style.css' )
);
wp_enqueue_script(
'my-script',
get_template_directory_uri() . '/js/main.js',
[ 'jquery' ],
filemtime( get_template_directory() . '/js/main.js' ),
true // Load in footer
);
wp_localize_script( 'my-script', 'MyData', [
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'my_nonce' ),
]);
}add_action( 'wp_enqueue_scripts', 'remove_unnecessary_assets', 100 );
function remove_unnecessary_assets(): void {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
wp_dequeue_style( 'wp-block-library' );
wp_dequeue_style( 'wp-block-library-theme' );
wp_dequeue_style( 'global-styles' );
}add_filter( 'login_redirect', 'redirect_after_login', 10, 3 );
function redirect_after_login( string $redirect_to, string $requested, $user ): string {
if ( isset( $user->roles ) && in_array( 'administrator', $user->roles, true ) ) {
return admin_url();
}
return home_url( '/dashboard/' );
}β‘οΈ See all 25 hook snippets
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'paged' => get_query_var( 'paged', 1 ),
'no_found_rows' => false,
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
the_title( '<h2>', '</h2>' );
endwhile;
wp_reset_postdata(); // ALWAYS reset after custom query
endif;$args = [
'post_type' => 'post',
'posts_per_page' => 5,
'no_found_rows' => true, // Skip COUNT(*) β no pagination needed
'update_post_meta_cache' => false, // Skip if not using post meta
'update_post_term_cache' => false, // Skip if not using terms
'fields' => 'ids', // Return IDs only β fastest
];global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT post_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value > %d",
'price',
100
),
ARRAY_A
);β‘οΈ See all 25 query snippets
// β NEVER
$name = $_POST['name'];
echo $_GET['search'];
$wpdb->query( "SELECT * FROM wp_posts WHERE ID = " . $_GET['id'] );
// β
ALWAYS
$name = sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) );
$search = esc_html( sanitize_text_field( wp_unslash( $_GET['search'] ?? '' ) ) );
$results = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", absint( $_GET['id'] ) ) );// Output nonce in your form
wp_nonce_field( 'save_my_options', 'my_nonce_field' );
// Verify on processing
add_action( 'admin_post_save_my_options', 'handle_save_my_options' );
function handle_save_my_options(): void {
if ( ! isset( $_POST['my_nonce_field'] ) ||
! wp_verify_nonce( sanitize_key( $_POST['my_nonce_field'] ), 'save_my_options' ) ) {
wp_die( 'Security check failed.' );
}
if ( ! current_user_can( 'manage_options' ) ) {
wp_die( 'Insufficient permissions.' );
}
// Process safely...
}// Add to the top of every PHP file in your plugin or theme
if ( ! defined( 'ABSPATH' ) ) {
exit;
}β‘οΈ See all 25 security snippets
function get_featured_posts(): array {
$cache_key = 'featured_posts_v1';
$cached = get_transient( $cache_key );
if ( false !== $cached ) {
return $cached;
}
$posts = get_posts([ 'meta_key' => '_is_featured', 'meta_value' => '1', 'numberposts' => 6 ]);
set_transient( $cache_key, $posts, HOUR_IN_SECONDS );
return $posts;
}
add_action( 'save_post', fn() => delete_transient( 'featured_posts_v1' ) );add_filter( 'heartbeat_settings', function( array $settings ): array {
$settings['interval'] = 60; // Default is 15 seconds
return $settings;
});add_filter( 'script_loader_tag', 'defer_non_critical_scripts', 10, 3 );
function defer_non_critical_scripts( string $tag, string $handle ): string {
$defer = [ 'my-chat-widget', 'cookie-notice' ];
if ( in_array( $handle, $defer, true ) ) {
return str_replace( ' src=', ' defer src=', $tag );
}
return $tag;
}β‘οΈ See all 25 performance snippets
add_filter( 'block_categories_all', 'register_my_block_category', 10, 2 );
function register_my_block_category( array $categories ): array {
return array_merge(
[[ 'slug' => 'my-plugin', 'title' => __( 'My Plugin Blocks', 'my-plugin' ), 'icon' => 'layout' ]],
$categories
);
}add_filter( 'use_block_editor_for_post_type', 'disable_gutenberg_for_post_types', 10, 2 );
function disable_gutenberg_for_post_types( bool $use_editor, string $post_type ): bool {
$classic_types = [ 'testimonial', 'faq', 'team_member' ];
return in_array( $post_type, $classic_types, true ) ? false : $use_editor;
}add_filter( 'render_block_core/paragraph', function( string $content ): string {
return str_replace( '<p', '<p data-block="paragraph"', $content );
});β‘οΈ See all 25 Gutenberg snippets
add_action( 'wp_ajax_my_action', 'handle_my_ajax' );
add_action( 'wp_ajax_nopriv_my_action', 'handle_my_ajax' );
function handle_my_ajax(): void {
check_ajax_referer( 'my_nonce_action', 'nonce' );
$post_id = absint( $_POST['post_id'] ?? 0 );
if ( ! $post_id ) {
wp_send_json_error( [ 'message' => 'Invalid post ID.' ] );
}
wp_send_json_success( [ 'post_id' => $post_id ] );
}const formData = new FormData();
formData.append( 'action', 'my_action' );
formData.append( 'nonce', MyData.nonce );
formData.append( 'post_id', postId );
const res = await fetch( MyData.ajax_url, { method: 'POST', body: formData });
const data = await res.json();
if ( data.success ) console.log( data.data );β‘οΈ See all 25 AJAX snippets
add_action( 'rest_api_init', function() {
register_rest_route( 'my-plugin/v1', '/posts/(?P<id>\d+)', [
'methods' => WP_REST_Server::READABLE,
'callback' => 'my_get_post',
'permission_callback' => '__return_true',
'args' => [
'id' => [ 'required' => true, 'sanitize_callback' => 'absint' ],
],
]);
});
function my_get_post( WP_REST_Request $request ): WP_REST_Response|WP_Error {
$post = get_post( $request->get_param( 'id' ) );
if ( ! $post || 'publish' !== $post->post_status ) {
return new WP_Error( 'not_found', 'Post not found.', [ 'status' => 404 ] );
}
return rest_ensure_response([
'id' => $post->ID,
'title' => get_the_title( $post ),
'link' => get_permalink( $post ),
]);
}β‘οΈ See all 25 REST API snippets
add_action( 'after_setup_theme', 'my_theme_setup' );
function my_theme_setup(): void {
load_theme_textdomain( 'my-theme', get_template_directory() . '/languages' );
add_theme_support( 'title-tag' );
add_theme_support( 'post-thumbnails' );
add_theme_support( 'html5', [ 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ] );
add_theme_support( 'wp-block-styles' );
add_theme_support( 'align-wide' );
register_nav_menus([
'primary' => __( 'Primary Menu', 'my-theme' ),
'footer' => __( 'Footer Menu', 'my-theme' ),
]);
}add_action( 'wp_head', 'output_open_graph_tags' );
function output_open_graph_tags(): void {
if ( ! is_singular() ) return;
echo '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '">' . "\n";
echo '<meta property="og:url" content="' . esc_url( get_permalink() ) . '">' . "\n";
echo '<meta property="og:image" content="' . esc_url( get_the_post_thumbnail_url( null, 'large' ) ) . '">' . "\n";
}β‘οΈ See all 25 theme snippets
<?php
/**
* Plugin Name: My Awesome Plugin
* Plugin URI: https://github.com/ahmodmusa/my-plugin
* Description: A brief description of what this plugin does.
* Version: 1.0.0
* Requires at least: 6.0
* Requires PHP: 8.0
* Author: Ahmod Musa
* Author URI: https://ahmodmusa.com
* License: GPL v2 or later
* Text Domain: my-plugin
*/
if ( ! defined( 'ABSPATH' ) ) exit;register_activation_hook( __FILE__, 'my_plugin_activate' );
function my_plugin_activate(): void {
add_option( 'my_plugin_version', '1.0.0' );
flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'my_plugin_deactivate' );
function my_plugin_deactivate(): void {
wp_clear_scheduled_hook( 'my_plugin_cron_hook' );
flush_rewrite_rules();
}β‘οΈ See all 25 plugin snippets
| Category | Snippets |
|---|---|
| πͺ Hooks | 25 |
| π WP_Query & Database | 25 |
| π Security | 25 |
| β‘ Performance | 25 |
| π§± Gutenberg | 25 |
| π AJAX | 25 |
| π REST API | 25 |
| π¨ Theme Development | 25 |
| π Plugin Development | 25 |
| Total | 225 |
Contributions are what make this repo great! π
- Fork the repo
- Create your branch:
git checkout -b snippet/my-snippet - Add your snippet following the contribution guidelines
- Commit:
git commit -m 'Add: short description' - Push:
git push origin snippet/my-snippet - Open a Pull Request
Please read CONTRIBUTING.md first.
If this saved you time:
- β Star this repo β it helps other developers find it!
- Share on Twitter/X with
#WordPress #WebDev #OpenSource - Post in WordPress Facebook groups or Slack channels
Built and maintained by Ahmod Musa β a WordPress developer passionate about clean code and helping the community.
- π Website: ahmodmusa.com
- πΌ Fiverr: fiverr.com/s/bd665oX
- π GitHub: github.com/ahmodmusa
Need custom WordPress development? Hire me on Fiverr β
MIT Β© Ahmod Musa
Made with β€οΈ for the WordPress community
β Star this repo if it helped you!