Code Snippets for WordPress

- Save
WordPress is a powerful and flexible content management system (CMS), but its true potential lies in its ability to be customized. While plugins offer a quick solution for most needs, they often come with extra features you don’t need—or worse, they can slow down your website. This is where custom code snippets come into play.
In this article, we’ll explore a wide range of useful code snippets—from improving security and boosting SEO to customizing the admin dashboard and front-end experience.
Note: You can use a Code manager plugin or directly paste PHP codes inside your theme file editor without any plugin.
Let’s Start.
Admin Customization
Display the featured image in the list of posts in the admin.
add_filter( 'manage_posts_columns', function ( $columns ) { $move_after = 'title'; $move_after_key = array_search( $move_after, array_keys( $columns ), true ); $first_columns = array_slice( $columns, 0, $move_after_key + 1 ); $last_columns = array_slice( $columns, $move_after_key + 1 ); return array_merge( $first_columns, array( 'featured_image' => __( 'Featured Image' ), ), $last_columns ); } ); add_action( 'manage_posts_custom_column', function ( $column ) { if ( 'featured_image' === $column ) { the_post_thumbnail( array( 300, 80 ) ); } } );
Disable Application passwords if not used on the website for better security.
add_filter('wp_is_application_passwords_available', '__return_false');
Add duplicate button to post/page list of actions.
add_filter( 'post_row_actions', 'wpcode_snippet_duplicate_post_link', 10, 2 ); add_filter( 'page_row_actions', 'wpcode_snippet_duplicate_post_link', 10, 2 ); if ( ! function_exists( 'wpcode_snippet_duplicate_post_link' ) ) { function wpcode_snippet_duplicate_post_link( $actions, $post ) { $post_type_object = get_post_type_object( $post->post_type ); if ( null === $post_type_object || ! current_user_can( $post_type_object->cap->create_posts ) ) { return $actions; } $url = wp_nonce_url( add_query_arg( array( 'action' => 'wpcode_snippet_duplicate_post', 'post_id' => $post->ID, ), 'admin.php' ), 'wpcode_duplicate_post_' . $post->ID, 'wpcode_duplicate_nonce' ); $actions['wpcode_duplicate'] = '<a href="' . $url . '" title="Duplicate item" rel="permalink">Duplicate</a>'; return $actions; } } add_action( 'admin_action_wpcode_snippet_duplicate_post', function () { if ( empty( $_GET['post_id'] ) ) { wp_die( 'No post id set for the duplicate action.' ); } $post_id = absint( $_GET['post_id'] ); if ( ! isset( $_GET['wpcode_duplicate_nonce'] ) || ! wp_verify_nonce( $_GET['wpcode_duplicate_nonce'], 'wpcode_duplicate_post_' . $post_id ) ) { wp_die( 'The link you followed has expired, please try again.' ); } $post = get_post( $post_id ); if ( $post ) { $current_user = wp_get_current_user(); $new_post = array( 'comment_status' => $post->comment_status, 'menu_order' => $post->menu_order, 'ping_status' => $post->ping_status, 'post_author' => $current_user->ID, 'post_content' => $post->post_content, 'post_excerpt' => $post->post_excerpt, 'post_name' => $post->post_name, 'post_parent' => $post->post_parent, 'post_password' => $post->post_password, 'post_status' => 'draft', 'post_title' => $post->post_title . ' (copy)',// Add "(copy)" to the title. 'post_type' => $post->post_type, 'to_ping' => $post->to_ping, ); $duplicate_id = wp_insert_post( $new_post ); $taxonomies = get_object_taxonomies( get_post_type( $post ) ); if ( $taxonomies ) { foreach ( $taxonomies as $taxonomy ) { $post_terms = wp_get_object_terms( $post_id, $taxonomy, array( 'fields' => 'slugs' ) ); wp_set_object_terms( $duplicate_id, $post_terms, $taxonomy ); } } $post_meta = get_post_meta( $post_id ); if ( $post_meta ) { foreach ( $post_meta as $meta_key => $meta_values ) { if ( '_wp_old_slug' === $meta_key ) { // skip old slug. continue; } foreach ( $meta_values as $meta_value ) { add_post_meta( $duplicate_id, $meta_key, maybe_unserialize( $meta_value ) ); } } } wp_safe_redirect( add_query_arg( array( 'action' => 'edit', 'post' => $duplicate_id ), admin_url( 'post.php' ) ) ); exit; } else { wp_die( 'Error loading post for duplication, please try again.' ); } } );
You can change the Post revision count here.
add_filter( 'wp_revisions_to_keep', function( $limit ) { // Limit to the last 20 revisions. Change 20 to whatever limit you want. return 20; } );
Force your authors to write posts that have a minimum length. (400 words Set here)
function wpcode_snippet_publish_min_words( $post_id, $post ) { // Edit the line below to set the desired minimum number of words. $word_count = 400; if ( str_word_count( $post->post_content ) < $word_count ) { wp_die( sprintf( // Translators: placeholder adds the minimum number of words. esc_html__( 'The post content is below the minimum word count. Your post needs to have at least %d words to be published.' ), absint( $word_count ) ) ); } } add_action( 'publish_post', 'wpcode_snippet_publish_min_words', 9, 2 );
By default, WordPress uses pagination to load media items, but with this snippet, it switches to an infinite scroll interface, allowing smoother and faster browsing of media files.
add_filter( 'media_library_infinite_scrolling', '__return_true' );
if (!current_user_can('administrator')) { add_filter('show_admin_bar', '__return_false'); }
By default, WordPress uses pagination to load media items, but with this snippet, it switches to an infinite scroll interface, allowing smoother and faster browsing of media files.
add_filter( 'media_library_infinite_scrolling', '__return_true' );
You can use the below code snippet to enable dark mode in WordPress Dashboard.
function applyCustomStyles() { echo ' <style> /* Change link colour to white */ #wpbody-content a { filter: invert(1) hue-rotate(180deg) saturate(10); color: white !important; } /* Change link colour to yellow */ #wpbody-content a:hover { filter: invert(1) hue-rotate(180deg) saturate(10); color: red !important; } /* Styling for primary content area. */ .block-editor-page .editor-styles-wrapper { color: lightgray; background: #262626; } /* Base styling adjustments. */ .wp-admin { background-color: #262626; } /* Image display corrections. */ .wp-admin #wpbody img { filter: invert(1) hue-rotate(-180deg); background: white; } /* Enhancements for hyperlink visuals. */ .block-editor-page .editor-styles-wrapper a { filter: invert(0.85) hue-rotate(185deg); } /* Filter reset for specific editor sections. */ .block-editor-page #wpbody { filter: unset; } /* Adjustments for the main body appearance. */ .wp-admin #wpbody { filter: invert(0.85) hue-rotate(185deg); } /* Sidebar appearance customization. */ .block-editor-page .interface-interface-skeleton__sidebar, .block-editor-page .interface-interface-skeleton__secondary-sidebar { filter: invert(0.85) hue-rotate(185deg); } /* Configuration for top navigation bar. */ .block-editor-page .interface-interface-skeleton__header { filter: invert(0.85) hue-rotate(185deg); } /* Primary action button styling. */ .block-editor-page .is-primary { color: black !important; } /* Lower section layout adjustments. */ .block-editor-page .edit-post-layout__metaboxes { border-top: 0px; background-color: #262626; } /* Reset various button BG colours */ .wrap .add-new-h2, .wrap .add-new-h2:active, .wrap .page-title-action, .wrap .page-title-action:active { background:#f6f7f700; } </style>'; } add_action('admin_head', 'applyCustomStyles');
Disable Gutenberg Editor and switch back to old Classic Editors and Widgets
add_filter('gutenberg_can_edit_post', '__return_false', 5); add_filter('use_block_editor_for_post', '__return_false', 5); add_filter( 'gutenberg_use_widgets_block_editor', '__return_false' ); add_filter( 'use_widgets_block_editor', '__return_false' );
By default, WordPress has no options on what is shown in the search results and shows everything. This includes posts, products, pages. You can only show posts in search results.
if (!is_admin()) { function wpb_search_filter($query) { if ($query->is_search) { $query->set('post_type', 'post'); } return $query; } add_filter('pre_get_posts','wpb_search_filter'); }
Enable SVG file uploads via the WordPress Media Library.
function allow_svg_upload( $mimes ) { $mimes['svg'] = 'image/svg+xml'; return $mimes; } add_filter( 'upload_mimes', 'allow_svg_upload' );
Enable SVG file uploads only for Admins.
function restrict_svg_upload_to_admins( $mimes ) { if ( current_user_can( 'administrator' ) ) { $mimes['svg'] = 'image/svg+xml'; } return $mimes; } add_filter( 'upload_mimes', 'restrict_svg_upload_to_admins' );
This code will enable the option to assign category to your Pages as well.
add_action( 'init', 'add_categories_to_pages' ); function add_categories_to_pages() { register_taxonomy_for_object_type( 'category', 'page' ); }
This code will enable the option to assign tags to WordPress Pages.
function add_tags_to_pages() { register_taxonomy_for_object_type('post_tag', 'page'); } add_action('init', 'add_tags_to_pages');
Performance
Prevent WordPress from automatically adding loading=”lazy” to images and iframes—useful if you’re using a custom lazy loading script or want better control over image loading behavior.
add_filter( 'wp_lazy_loading_enabled', '__return_false' );
Prevent loading the Dashicons font library on the front end for non-logged-in users to improve performance.
function dequeue_dashicons_for_guests() { if ( ! is_user_logged_in() ) { wp_dequeue_style( 'dashicons' ); } } add_action( 'wp_enqueue_scripts', 'dequeue_dashicons_for_guests' );
To remove the Gutenberg Block Library CSS from the front end of your WordPress site, use the following snippet. This is especially useful if you’re not using the Gutenberg editor or want to reduce unnecessary CSS being loaded.
function remove_wp_block_library_css() { wp_dequeue_style( 'wp-block-library' ); wp_dequeue_style( 'wp-block-library-theme' ); wp_dequeue_style( 'global-styles' ); // For theme.json styles } add_action( 'wp_enqueue_scripts', 'remove_wp_block_library_css', 100 );
You don’t need a Image optimization plugin to convert images to webp format. Just use the code snippets below.
/** * Convert Uploaded Images to WebP Format * * This snippet automatically converts JPEG, PNG, and GIF images * to WebP format during the upload process. */ add_filter('wp_handle_upload', 'wpturbo_handle_upload_convert_to_webp'); function wpturbo_handle_upload_convert_to_webp($upload) { if (in_array($upload['type'], ['image/jpeg', 'image/png', 'image/gif'])) { $file_path = $upload['file']; if (extension_loaded('imagick') || extension_loaded('gd')) { $image_editor = wp_get_image_editor($file_path); if (!is_wp_error($image_editor)) { $file_info = pathinfo($file_path); $dirname = $file_info['dirname']; $filename = $file_info['filename']; $def_filename = wp_unique_filename($dirname, $filename . '.webp'); $new_file_path = $dirname . '/' . $def_filename; $saved_image = $image_editor->save($new_file_path, 'image/webp'); if (!is_wp_error($saved_image) && file_exists($saved_image['path'])) { // Update the upload data to use the WebP image $upload['file'] = $saved_image['path']; $upload['url'] = str_replace(basename($upload['url']), basename($saved_image['path']), $upload['url']); $upload['type'] = 'image/webp'; // Optionally delete the original file @unlink($file_path); } } } } return $upload; }
WooCommerce
You can hide all unused checkout field in your WooCommerce website using the simple code snippets.
add_filter('woocommerce_checkout_fields', 'custom_override_checkout_fields'); function custom_override_checkout_fields($fields) { // Check if cart has virtual or downloadable products $has_virtual_or_downloadable = false; foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) { if ($cart_item['data']->is_virtual() || $cart_item['data']->is_downloadable()) { $has_virtual_or_downloadable = true; break; } } if ($has_virtual_or_downloadable) { // Remove unwanted billing fields unset($fields['billing']['billing_company']); unset($fields['billing']['billing_address_1']); unset($fields['billing']['billing_address_2']); unset($fields['billing']['billing_city']); unset($fields['billing']['billing_postcode']); unset($fields['billing']['billing_country']); unset($fields['billing']['billing_state']); unset($fields['billing']['billing_phone']); // Remove order comments field unset($fields['order']['order_comments']); // Remove account-related fields unset($fields['account']['account_username']); unset($fields['account']['account_password']); unset($fields['account']['account_password-2']); } return $fields; } // Removes Order Notes Title – Additional Information & Notes Field add_filter('woocommerce_enable_order_notes_field', '__return_false', 9999); // Remove Order Notes Field add_filter('woocommerce_checkout_fields', 'remove_order_notes'); function remove_order_notes($fields) { unset($fields['order']['order_comments']); return $fields; }
If you are selling both Digital and physical product on your website and want autocomplete only on virtual and downloadable products after successful payment than you can use the below code. Learn more about WooCommerce Autocomplete orders here.
add_filter( 'woocommerce_payment_complete_order_status', 'auto_complete_virtual_orders', 10, 3 ); function auto_complete_virtual_orders( $payment_complete_status, $order_id, $order ) { $current_status = $order->get_status(); // We only want to update the status to 'completed' if it's coming from one of the following statuses: $allowed_current_statuses = array( 'on-hold', 'pending', 'failed' ); if ( 'processing' === $payment_complete_status && in_array( $current_status, $allowed_current_statuses ) ) { $order_items = $order->get_items(); // Create an array of products in the order $order_products = array_filter( array_map( function( $item ) { // Get associated product for each line item return $item->get_product(); }, $order_items ), function( $product ) { // Remove non-products return !! $product; } ); if ( count( $order_products ) > 0 ) { // Corrected line // Check if each product is 'virtual' $is_virtual_order = array_reduce( $order_products, function( $virtual_order_so_far, $product ) { return $virtual_order_so_far && $product->is_virtual(); }, true ); if ( $is_virtual_order ) { $payment_complete_status = 'completed'; } } } return $payment_complete_status; }
By using a code snippets like this, You will be able to clean up images that are currently not attached to any existing product pages.
// Automatically Delete Woocommerce Images After Deleting a Product add_action( 'before_delete_post', 'delete_product_images', 10, 1 ); function delete_product_images( $post_id ) { if ( !current_user_can( 'delete_products' ) ) { return; } $product = wc_get_product( $post_id ); if ( !$product ) { return; } $featured_image_id = $product->get_image_id(); $image_galleries_id = $product->get_gallery_image_ids(); if( !empty( $featured_image_id ) ) { $is_featured_image_used = is_image_used( $featured_image_id, $post_id ); if ( !$is_featured_image_used ) { wp_delete_attachment( $featured_image_id, true ); } } if( !empty( $image_galleries_id ) ) { foreach( $image_galleries_id as $single_image_id ) { $is_image_used = is_image_used( $single_image_id, $post_id ); if ( !$is_image_used ) { wp_delete_attachment( $single_image_id, true ); } } } } function is_image_used( $image_id, $current_product_id ) { $query = new WP_Query( array( 'post_type' => 'product', 'post_status' => 'publish', 'meta_query' => array( 'relation' => 'OR', array( 'key' => '_thumbnail_id', 'value' => $image_id, 'compare' => '=' ), array( 'key' => '_product_image_gallery', 'value' => '"'.$image_id.'"', 'compare' => 'LIKE' ) ), 'post__not_in' => array( $current_product_id ), 'fields' => 'ids', 'posts_per_page' => -1 ) ); return ( $query->have_posts() ); }
SEO
Display Featured image in WordPress Default RSS Feed
function mcw_featured_image_in_feeds($content) { global $post; if ( has_post_thumbnail( $post->ID ) ){ $content = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content; } return $content; } add_filter('the_excerpt_rss', 'mcw_featured_image_in_feeds'); add_filter('the_content_feed', 'mcw_featured_image_in_feeds');
Set a default Fallback Featured image for all posts that doesn’t have featured image.
function my_filter_thumbnail_id( $thumbnail_id, $post = null ) { if ( ! $thumbnail_id ) { $thumbnail_id = 4571; //id of default featured image } return $thumbnail_id; } add_filter( 'post_thumbnail_id', 'my_filter_thumbnail_id', 20, 5 );
If you want me to include any specific code snippets for Wordpress or want any modification or found any issue in any of the code snippets then do let me know in comment section.
Sharing is caring ❤️