25 Useful WordPress PHP Snippets
WordPress provides an extensive collection of functions, actions and filters that allow website behaviour to be modified without editing core files. Many common customisations require only a small amount of PHP, particularly changes to the administration area, content display, user management and front-end functionality.
A carefully selected collection of PHP snippets can replace some single-purpose plugins, although reducing the number of plugins does not automatically improve performance or security. Custom code still requires maintenance, compatibility checks and appropriate security controls.
The examples below use standard WordPress APIs and are intended for modern WordPress installations. Each snippet addresses a specific task, with implementation notes explaining where it operates and any significant restrictions.
Where to Add WordPress PHP Snippets
The safest location depends on the purpose of the code.
A code snippets plugin provides a convenient interface for enabling, disabling and organising small PHP customisations. This is generally suitable for website administrators who do not want to maintain plugin files manually.
A small custom functionality plugin is preferable when several related snippets need to remain active independently of the current theme. It also provides a more portable way to maintain site-specific functionality.
A child theme’s functions.php file is appropriate for customisations specifically associated with that theme. Functionality that must survive a theme change generally belongs in a plugin instead.
Avoid editing WordPress core files or a parent theme’s functions.php. Changes to these files may be overwritten during updates.
For a standalone functionality plugin, create a PHP file inside its own directory under wp-content/plugins/. The following example provides the basic structure:
<?php /** * Plugin Name: Site Custom Functions * Description: Site-specific WordPress customisations. * Version: 1.0.0 */ defined( 'ABSPATH' ) || exit;
Additional snippets can be inserted below this header. The plugin can then be activated from the WordPress administration area.
Important: The examples below are individual snippets, not 25 separate complete plugins. When inserting them into an existing PHP file or PHP-mode snippets editor, do not add another opening <?php tag if one is already present.
The examples use the site_ prefix for custom function names. A distinctive prefix reduces the possibility of conflicts with WordPress core, themes and other plugins.
Test changes on a staging website where possible and ensure a working backup is available before modifying production code.
WordPress Administration Customisations
1. Remove Unnecessary Dashboard Widgets
The WordPress dashboard can contain widgets that are irrelevant to a particular website. Removing them can simplify the administration area, especially for users who primarily create and manage content.
function site_remove_dashboard_widgets() {
remove_meta_box(
'dashboard_quick_press',
'dashboard',
'side'
);
remove_meta_box(
'dashboard_primary',
'dashboard',
'side'
);
remove_meta_box(
'dashboard_activity',
'dashboard',
'normal'
);
}
add_action(
'wp_dashboard_setup',
'site_remove_dashboard_widgets'
);
This removes the Quick Draft, WordPress Events and News, and Activity dashboard widgets where those standard widget IDs are registered.
The widgets are removed from the dashboard interface rather than deleted from WordPress.
Additional widgets can be removed by identifying their registered IDs. Third-party plugins may introduce dashboard widgets with different IDs.
2. Add a Custom Dashboard Widget
A dashboard widget can provide internal information such as editorial instructions, support contacts or maintenance reminders.
function site_dashboard_widget_content() {
echo '<p>';
echo esc_html(
'Check pending updates and review recent backups.'
);
echo '</p>';
}
function site_register_dashboard_widget() {
wp_add_dashboard_widget(
'site_maintenance_widget',
'Website Maintenance',
'site_dashboard_widget_content'
);
}
add_action(
'wp_dashboard_setup',
'site_register_dashboard_widget'
);
The wp_add_dashboard_widget() function registers a dashboard widget with a unique identifier, title and display callback.
The example outputs fixed text using esc_html().
For a more advanced widget, the callback could retrieve information from WordPress options or other internal data sources. Dynamic values must be escaped appropriately when displayed.
3. Change the WordPress Admin Footer Text
The administration footer can display a custom message instead of the default WordPress footer text.
function site_custom_admin_footer( $text ) {
return 'Website Administration';
}
add_filter(
'admin_footer_text',
'site_custom_admin_footer'
);
The admin_footer_text filter receives the existing footer content and allows it to be replaced.
This affects the administration interface only.
The returned value is fixed text. If the footer text is later generated from user-controlled data, appropriate output escaping should be applied.
4. Add a Custom Column to the Posts List
Custom columns can make the posts administration screen more useful.
The following example adds a column showing the numeric ID of each post.
function site_add_post_id_column( $columns ) {
$columns['site_post_id'] = 'Post ID';
return $columns;
}
add_filter(
'manage_posts_columns',
'site_add_post_id_column'
);
function site_display_post_id_column(
$column,
$post_id
) {
if ( 'site_post_id' === $column ) {
echo esc_html( (string) $post_id );
}
}
add_action(
'manage_posts_custom_column',
'site_display_post_id_column',
10,
2
);
The first callback registers the column. The second supplies its content.
Post IDs are useful when working with shortcodes, custom queries, debugging and content relationships.
The example applies to the standard posts list. Custom post types may require their own column hooks.
5. Add a Custom Column to the Pages List
The pages administration screen can use separate column hooks.
This example displays the last modified date for each page.
function site_add_page_modified_column( $columns ) {
$columns['site_modified'] = 'Last Modified';
return $columns;
}
add_filter(
'manage_pages_columns',
'site_add_page_modified_column'
);
function site_display_page_modified_column(
$column,
$post_id
) {
if ( 'site_modified' !== $column ) {
return;
}
$timestamp = get_post_modified_time(
'U',
true,
$post_id
);
if ( ! $timestamp ) {
return;
}
echo esc_html(
wp_date(
get_option( 'date_format' ),
(int) $timestamp
)
);
}
add_action(
'manage_pages_custom_column',
'site_display_page_modified_column',
10,
2
);
The timestamp is retrieved from the page’s modification date and formatted using the site’s configured date format.
This is useful when managing a website with many static pages, product information pages or reference documents.
The value reflects the page’s stored modification timestamp. It does not necessarily indicate when cached content was last refreshed or when a visitor last saw the updated page.
6. Hide Selected Administration Menu Items
Some websites contain menu items that particular users rarely need.
The following snippet hides the Comments menu for users who cannot manage site options.
function site_hide_comments_menu() {
if ( current_user_can( 'manage_options' ) ) {
return;
}
remove_menu_page( 'edit-comments.php' );
}
add_action(
'admin_menu',
'site_hide_comments_menu',
999
);
The remove_menu_page() function removes a menu entry from the administration navigation.
It does not revoke access to the underlying screen. WordPress capabilities determine whether a user is permitted to perform an action.
Security distinction: Hiding an administration menu must never be treated as a substitute for permission checks.
7. Add a Custom Administration Notice
Administration notices can remind site managers about configuration or maintenance requirements.
function site_custom_admin_notice() {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$screen = get_current_screen();
if (
! $screen ||
'dashboard' !== $screen->id
) {
return;
}
echo '<div class="notice notice-info">';
echo '<p>';
echo esc_html(
'Review website backups before applying major updates.'
);
echo '</p>';
echo '</div>';
}
add_action(
'admin_notices',
'site_custom_admin_notice'
);
This displays an informational notice on the dashboard for users with the manage_options capability.
The dashboard restriction prevents the message from appearing throughout the administration area.
For notices that must be dismissed permanently, an additional mechanism is required to record each user’s preference.
8. Add a Link to the WordPress Admin Toolbar
The administration toolbar can provide quick access to frequently used screens.
The following example adds a link to the Media Library.
function site_add_toolbar_link( $wp_admin_bar ) {
if ( ! current_user_can( 'upload_files' ) ) {
return;
}
$wp_admin_bar->add_node(
array(
'id' => 'site_media_link',
'title' => 'Media Library',
'href' => admin_url( 'upload.php' ),
)
);
}
add_action(
'admin_bar_menu',
'site_add_toolbar_link',
100
);
The callback receives the WP_Admin_Bar object.
The upload_files capability check limits the link to users permitted to access relevant media functionality.
The toolbar node can be extended with additional properties, including a parent node or HTML attributes.
Content Display and Publishing
9. Change the Default Excerpt Length
WordPress automatically generates excerpts when a post does not have a manually written excerpt.
The default generated excerpt length can be changed using the excerpt_length filter.
function site_custom_excerpt_length( $length ) {
return 30;
}
add_filter(
'excerpt_length',
'site_custom_excerpt_length',
999
);
This requests a maximum of 30 words for automatically generated excerpts.
The high filter priority helps ensure that the custom value is applied after common lower-priority filters.
The filter does not necessarily control every excerpt displayed on the website. Themes, blocks and plugins may apply their own excerpt limits or use separate rendering functions.
Manually entered excerpts are not shortened by this filter alone.
10. Change the Excerpt More Text
Automatically generated excerpts often end with an ellipsis-style indicator.
The excerpt_more filter allows this text to be changed.
function site_custom_excerpt_more( $more ) {
return '...';
}
add_filter(
'excerpt_more',
'site_custom_excerpt_more'
);
The callback returns the replacement text for the automatically generated excerpt ending.
This example uses three ordinary periods.
It does not add a link to the complete article. A theme or block may already provide a separate read-more link.
The filter applies to the WordPress excerpt-generation process, not every custom excerpt implementation.
11. Display an Estimated Reading Time
A reading-time estimate can be useful on websites publishing lengthy articles.
The following shortcode calculates the approximate reading time of the current post.
function site_reading_time_shortcode() {
$post = get_post();
if ( ! $post instanceof WP_Post ) {
return '';
}
$content = strip_shortcodes( $post->post_content );
$content = wp_strip_all_tags( $content );
$words = str_word_count(
wp_decode_entities( $content )
);
$minutes = max(
1,
(int) ceil( $words / 200 )
);
return esc_html(
sprintf(
'%d min read',
$minutes
)
);
}
add_shortcode(
'site_reading_time',
'site_reading_time_shortcode'
);
Insert the following shortcode into a post or a shortcode-compatible block:
[site_reading_time]
The calculation assumes an average reading speed of 200 words per minute.
The result is approximate. str_word_count() is most suitable for languages with conventional whitespace-separated words and may not count all languages or Unicode characters accurately.
Rendered content can also differ from the raw stored post content, particularly when blocks, shortcodes or dynamic content are involved.
12. Display the Last Modified Date
For technical articles, reference material and troubleshooting guides, the last modified date can be more relevant than the original publication date.
function site_modified_date_shortcode() {
$post = get_post();
if ( ! $post instanceof WP_Post ) {
return '';
}
$timestamp = get_post_modified_time(
'U',
true,
$post
);
if ( ! $timestamp ) {
return '';
}
return esc_html(
wp_date(
get_option( 'date_format' ),
(int) $timestamp
)
);
}
add_shortcode(
'site_modified_date',
'site_modified_date_shortcode'
);
Usage:
[site_modified_date]
The output uses the site’s configured date format.
This provides a simple way to display the stored modification date without changing the theme’s template files.
The modification date should not be described as a verification or review date unless the content was actually checked.
13. Display the Current Year Automatically
A current-year shortcode can be used in copyright notices, footers and other content that changes annually.
function site_current_year_shortcode() {
return esc_html(
wp_date( 'Y' )
);
}
add_shortcode(
'site_current_year',
'site_current_year_shortcode'
);
Usage:
[site_current_year]
The shortcode uses wp_date() so that the year is calculated using WordPress’s configured timezone.
This matters around New Year’s Day, when the server timezone and website timezone may differ.
The shortcode is evaluated when the page is generated. If the page is served from a full-page cache, its output may remain unchanged until that cache is refreshed.
14. Display an Author Biography
An author biography can be displayed using WordPress’s built-in user profile information.
The following shortcode retrieves the description associated with the current post’s author.
function site_author_bio_shortcode() {
$post = get_post();
if ( ! $post instanceof WP_Post ) {
return '';
}
$author_id = (int) $post->post_author;
if ( ! $author_id ) {
return '';
}
$bio = get_the_author_meta(
'description',
$author_id
);
if ( empty( $bio ) ) {
return '';
}
return '<div class="site-author-bio">' .
wpautop( esc_html( $bio ) ) .
'</div>';
}
add_shortcode(
'site_author_bio',
'site_author_bio_shortcode'
);
Usage:
[site_author_bio]
The function retrieves the author’s profile description rather than the post content.
The biography is escaped before being formatted into paragraphs. This means any HTML entered in the biography is displayed as text rather than interpreted as markup.
The surrounding CSS class can be styled through the theme or an appropriate stylesheet.
15. Display Recent Posts with a Shortcode
A recent-posts list is useful for resource pages, category introductions and website navigation.
function site_recent_posts_shortcode( $atts ) {
$atts = shortcode_atts(
array(
'count' => 5,
),
$atts,
'site_recent_posts'
);
$count = max(
1,
min( 20, absint( $atts['count'] ) )
);
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $count,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
)
);
if ( ! $query->have_posts() ) {
return '';
}
$output = '<ul class="site-recent-posts">';
while ( $query->have_posts() ) {
$query->the_post();
$output .= '<li><a href="' .
esc_url( get_permalink() ) .
'">' .
esc_html( get_the_title() ) .
'</a></li>';
}
wp_reset_postdata();
$output .= '</ul>';
return $output;
}
add_shortcode(
'site_recent_posts',
'site_recent_posts_shortcode'
);
Usage:
[site_recent_posts count="5"]
The count attribute determines how many posts appear, with the example restricting the value to between 1 and 20.
The query retrieves published standard posts and excludes sticky-post prioritisation.
Using no_found_rows avoids calculating the total number of matching posts when pagination is unnecessary.
The wp_reset_postdata() call restores the previous global post context after the custom loop.
16. Display Posts from a Specific Category
A category-based shortcode is useful for building themed resource pages.
For example, a page about WordPress performance could display the latest articles from a performance category.
function site_category_posts_shortcode( $atts ) {
$atts = shortcode_atts(
array(
'category' => '',
'count' => 5,
),
$atts,
'site_category_posts'
);
$category = sanitize_title(
$atts['category']
);
if ( '' === $category ) {
return '';
}
$count = max(
1,
min( 20, absint( $atts['count'] ) )
);
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => $category,
'posts_per_page' => $count,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
)
);
if ( ! $query->have_posts() ) {
return '';
}
$output = '<ul class="site-category-posts">';
while ( $query->have_posts() ) {
$query->the_post();
$output .= '<li><a href="' .
esc_url( get_permalink() ) .
'">' .
esc_html( get_the_title() ) .
'</a></li>';
}
wp_reset_postdata();
$output .= '</ul>';
return $output;
}
add_shortcode(
'site_category_posts',
'site_category_posts_shortcode'
);
Usage:
[site_category_posts category="performance" count="6"]
The category attribute expects a category slug, not its display name.
The query returns published standard posts assigned to that category.
If the category does not exist or no matching posts are found, the shortcode returns an empty string.
17. Create a Reusable Information Box Shortcode
A custom shortcode can produce consistent information boxes without requiring the same markup to be inserted manually into multiple articles.
function site_notice_box_shortcode(
$atts,
$content = null
) {
$atts = shortcode_atts(
array(
'title' => 'Note',
),
$atts,
'site_notice_box'
);
if ( null === $content ) {
return '';
}
$title = sanitize_text_field(
$atts['title']
);
$body = wpautop(
esc_html( $content )
);
return '<aside class="site-notice-box">' .
'<strong>' .
esc_html( $title ) .
'</strong>' .
$body .
'</aside>';
}
add_shortcode(
'site_notice_box',
'site_notice_box_shortcode'
);
Usage:
[site_notice_box title="Important"] Back up your website before making configuration changes. [/site_notice_box]
The shortcode uses an enclosing format, allowing content to be placed between opening and closing tags.
Both the title and body are treated as plain text. HTML entered inside the shortcode is escaped.
A CSS rule targeting .site-notice-box can provide consistent borders, spacing and background styling.
For more elaborate callouts containing nested blocks or rich formatting, a native WordPress block may be more suitable.
Users, Comments and Access
18. Disable Comments on New Pages
WordPress supports comments on both posts and pages, although many websites do not need discussion threads on static pages.
The following snippet disables comments and pingbacks when a new page is inserted, or when the page is inserted as a draft that will be published later.
function site_disable_new_page_comments(
$data,
$postarr
) {
if (
isset( $data['post_type'] ) &&
'page' === $data['post_type'] &&
empty( $postarr['ID'] )
) {
$data['comment_status'] = 'closed';
$data['ping_status'] = 'closed';
}
return $data;
}
add_filter(
'wp_insert_post_data',
'site_disable_new_page_comments',
10,
2
);
The wp_insert_post_data filter allows post data to be modified before insertion into the database.
This example applies only when inserting a new page. Existing pages are unaffected.
The comment_status and ping_status fields control comments and pingbacks respectively.
This is not a complete site-wide comments-disabling system. Existing pages may still have open discussions, and plugins may provide alternative comment functionality.
19. Redirect Users After Login
WordPress provides the login_redirect filter to modify the destination after a successful login.
The following snippet sends users with the edit_posts capability to the administration dashboard, while users without that capability are sent to the website homepage.
function site_custom_login_redirect(
$redirect_to,
$requested_redirect_to,
$user
) {
if ( ! $user instanceof WP_User ) {
return $redirect_to;
}
if ( user_can( $user, 'edit_posts' ) ) {
return admin_url();
}
return home_url( '/' );
}
add_filter(
'login_redirect',
'site_custom_login_redirect',
10,
3
);
This demonstrates a capability-based redirect rather than checking for a particular role name.
Capabilities are generally more suitable than role names when determining whether users can perform WordPress operations.
The third argument may contain a WP_Error object when authentication fails, so the callback checks that it has a valid WP_User object.
This example deliberately overrides the usual requested destination after login. That can be undesirable on websites using membership systems, checkout flows or specialised authentication plugins.
For such websites, retaining valid requested destinations is often preferable.
20. Display a Login or Logout Link
A shortcode can display either a login link or a logout link according to the visitor’s authentication status.
function site_login_logout_shortcode() {
if ( is_user_logged_in() ) {
$url = wp_logout_url( home_url( '/' ) );
$label = 'Log out';
} else {
$url = wp_login_url();
$label = 'Log in';
}
return '<a href="' .
esc_url( $url ) .
'">' .
esc_html( $label ) .
'</a>';
}
add_shortcode(
'site_login_logout',
'site_login_logout_shortcode'
);
Usage:
[site_login_logout]
The logout URL is generated through the WordPress API, which incorporates the appropriate logout nonce.
When the visitor is logged out, the shortcode displays a login link.
When the visitor is logged in, it displays a logout link that redirects to the homepage after logout.
Caching consideration: The result depends on the visitor’s login status. Do not place it in a publicly shared full-page cache unless the caching system correctly handles personalised content.
Additional Development and Configuration Snippets
21. Limit the Number of Stored Post Revisions
WordPress can retain multiple revisions of posts and pages. These provide a recovery mechanism when content is changed or accidentally overwritten.
The number of revisions retained can be controlled with the wp_revisions_to_keep filter.
function site_limit_post_revisions(
$num,
$post
) {
if ( 'post' === $post->post_type ) {
return 10;
}
if ( 'page' === $post->post_type ) {
return 5;
}
return $num;
}
add_filter(
'wp_revisions_to_keep',
'site_limit_post_revisions',
10,
2
);
This example retains up to 10 revisions for standard posts and five for pages, while leaving other post types unchanged.
The filter receives both the existing revision limit and the relevant post object.
A revision limit does not immediately delete all older revisions already stored in the database. It controls revision retention as WordPress processes subsequent changes.
Reducing revisions can limit future database growth, but it also reduces the amount of editing history available for recovery.
22. Register a Custom Image Size
WordPress can generate additional image sizes when files are uploaded to the Media Library.
A custom size is useful when a website needs consistent dimensions for particular content.
function site_register_image_sizes() {
add_image_size(
'site-resource-thumbnail',
600,
400,
true
);
}
add_action(
'after_setup_theme',
'site_register_image_sizes'
);
The arguments specify:
-
A unique image size identifier.
-
Maximum output width of 600 pixels.
-
Maximum output height of 400 pixels.
-
Hard cropping enabled.
With hard cropping, WordPress attempts to produce an image with the specified dimensions, subject to the dimensions of the original image and image-processing capabilities.
The registered size can be used with WordPress image functions:
echo get_the_post_thumbnail(
get_the_ID(),
'site-resource-thumbnail'
);
The second example is a template fragment intended for use inside an appropriate post context, rather than a complete standalone snippet.
Registering a new image size does not automatically generate it for previously uploaded images. Existing attachments may require thumbnail regeneration.
Additional generated image sizes also increase the storage space required by the Media Library.
23. Register a Custom Post Type
Custom post types allow WordPress to manage content that does not fit naturally into standard posts or pages.
A resource website, for example, might use a separate content type for downloadable references.
function site_register_resource_post_type() {
register_post_type(
'site_resource',
array(
'labels' => array(
'name' => 'Resources',
'singular_name' => 'Resource',
'add_new_item' => 'Add New Resource',
'edit_item' => 'Edit Resource',
),
'public' => true,
'has_archive' => true,
'show_in_rest' => true,
'menu_icon' => 'dashicons-media-document',
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'revisions',
),
'rewrite' => array(
'slug' => 'resources',
),
)
);
}
add_action(
'init',
'site_register_resource_post_type'
);
The register_post_type() function creates a content type with its own administration interface.
The show_in_rest argument enables REST API exposure and compatibility with the block editor.
The supports array controls the standard editing features available for the new type.
The rewrite argument defines the public URL structure.
After introducing a new custom post type with rewritten URLs, visit Settings > Permalinks and save the settings to regenerate rewrite rules if necessary.
Do not call flush_rewrite_rules() on every page load. A production plugin should handle rewrite-rule flushing during appropriate activation or update operations.
Custom post types are usually better registered in a plugin than in a theme, so content remains registered when the site’s appearance changes.
24. Restrict WordPress Search to Standard Posts
By default, WordPress search can include more than one public post type, depending on the site’s configuration.
The pre_get_posts action can modify the main search query before it executes.
function site_search_posts_only( $query ) {
if (
is_admin() ||
! $query->is_main_query() ||
! $query->is_search()
) {
return;
}
$query->set(
'post_type',
'post'
);
}
add_action(
'pre_get_posts',
'site_search_posts_only'
);
This restricts the main public-facing search query to standard posts.
The is_admin() condition prevents the modification from affecting ordinary administration queries.
The is_main_query() check avoids modifying secondary queries created by widgets, shortcodes or other components.
Use the query object’s is_search() method rather than relying on global conditional functions when modifying a query through pre_get_posts.
This change is unsuitable if the website relies on WordPress search to find products, pages, custom post types or other content.
Search plugins may also implement their own query handling, which can change the effect of this filter.
25. Create a Simple Related Posts Shortcode
Related posts help visitors discover additional content within the same subject area.
The following shortcode finds published posts that share at least one category with the current post.
function site_related_posts_shortcode( $atts ) {
$post = get_post();
if (
! $post instanceof WP_Post ||
'post' !== $post->post_type
) {
return '';
}
$atts = shortcode_atts(
array(
'count' => 5,
),
$atts,
'site_related_posts'
);
$count = max(
1,
min( 10, absint( $atts['count'] ) )
);
$categories = wp_get_post_categories(
$post->ID
);
if ( empty( $categories ) ) {
return '';
}
$query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => $count,
'post__not_in' => array( $post->ID ),
'category__in' => $categories,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
)
);
if ( ! $query->have_posts() ) {
return '';
}
$output = '<ul class="site-related-posts">';
while ( $query->have_posts() ) {
$query->the_post();
$output .= '<li><a href="' .
esc_url( get_permalink() ) .
'">' .
esc_html( get_the_title() ) .
'</a></li>';
}
wp_reset_postdata();
$output .= '</ul>';
return $output;
}
add_shortcode(
'site_related_posts',
'site_related_posts_shortcode'
);
Usage:
[site_related_posts count="5"]
The shortcode identifies the current post’s categories, then retrieves other published posts assigned to at least one of those categories.
The post__not_in argument prevents the current post from appearing in the results.
The category__in argument accepts an array of category IDs.
Using no_found_rows reduces unnecessary query work because the result is not paginated.
This is a straightforward category-based related-content mechanism. It does not calculate semantic similarity or rank articles according to their actual subject matter.
For a small or medium-sized reference website with carefully maintained categories, the approach can still provide useful internal navigation.
Choosing Which Snippets to Use
Not every WordPress website benefits from every customisation. Snippets should be selected according to specific requirements rather than installed as a collection simply because they are available.
| Snippet | Primary purpose | Main consideration |
|---|---|---|
| 1. Remove dashboard widgets | Simplify administration | Widget IDs |
| 2. Custom dashboard widget | Display internal information | Access and output escaping |
| 3. Admin footer text | Customise administration | Administration only |
| 4. Post ID column | Improve post management | Column hook compatibility |
| 5. Modified date column | Track page changes | Stored modification dates |
| 6. Hide admin menu | Simplify navigation | Does not change permissions |
| 7. Admin notice | Display internal reminders | Capability checks |
| 8. Toolbar link | Improve navigation | User capabilities |
| 9. Excerpt length | Adjust generated summaries | Theme and plugin overrides |
| 10. Excerpt ending | Change summary formatting | Generated excerpts only |
| 11. Reading time | Display reading estimate | Word-count accuracy |
| 12. Modified date | Display content freshness information | Date is not verification |
| 13. Current year | Automatically update year | Page caching |
| 14. Author biography | Display author information | Profile content |
| 15. Recent posts | Display recent articles | Query efficiency |
| 16. Category posts | Create themed lists | Category slug accuracy |
| 17. Information box | Reuse article formatting | Plain-text content |
| 18. Disable new-page comments | Control discussion settings | Existing pages unaffected |
| 19. Login redirect | Control login destination | Membership and checkout flows |
| 20. Login/logout link | Display authentication link | Personalised caching |
| 21. Limit revisions | Control editing history | Recovery requirements |
| 22. Custom image size | Standardise image dimensions | Storage and regeneration |
| 23. Custom post type | Organise specialised content | Rewrite rules |
| 24. Search posts only | Control search results | Excludes other content types |
| 25. Related posts | Improve internal navigation | Additional database queries |
Maintaining Custom WordPress Code
Custom snippets should be managed with the same care as ordinary plugins. They execute within WordPress and may affect both the reliability and security of the website.
A practical arrangement is to maintain a single site-specific functionality plugin containing related functions. Each function should have a distinctive prefix, and the plugin should be placed under version control if the code is substantial enough to justify ongoing development.
Avoid copying the same function into multiple locations. PHP functions declared in the global namespace cannot normally be redeclared. Duplicate function names can produce fatal errors, even if the functions contain identical code.
When a snippet changes a WordPress hook, database query or user-facing feature, record its intended behaviour. A short description of the affected screen or functionality is often sufficient to make future maintenance easier.
WordPress updates may introduce changes to APIs, execution order or block rendering that affect previously working customisations. Third-party plugins can also alter content through the same hooks. Review active customisations periodically, particularly after major updates.
For code that is no longer required, disable it before deleting it permanently. This provides an opportunity to confirm that no pages, templates or shortcodes still depend on the functionality.
Troubleshooting Custom Snippets
| Symptom | Possible cause | Diagnostic action |
|---|---|---|
| PHP fatal error | Duplicate function name | Search active code for repeated declarations |
| Snippet has no effect | Incorrect hook or execution context | Confirm hook registration and where it executes |
| Admin change not visible | Wrong screen or menu identifier | Inspect the affected administration screen |
| Shortcode appears as text | Shortcode not registered or not processed | Confirm code is active and shortcode syntax is correct |
| Shortcode returns nothing | Missing post context or no matching content | Check callback conditions and query results |
| Unexpected content output | Callback echoes instead of returning | Return generated shortcode markup |
| Site search changes unexpectedly | Query filter modifies unrelated queries | Check main-query and context conditions |
| PHP warnings | Incorrect argument types or missing values | Inspect the debug log and validate callback inputs |
| Custom image size unavailable | Existing image lacks generated size | Check registration and regenerate where appropriate |
| Custom post type URLs return 404 | Rewrite rules not updated | Save permalink settings after registration |
| Page content remains unchanged | Full-page or object caching | Identify which cache holds the previous result |
| Feature conflicts with plugin | Competing hooks or functionality | Isolate the responsible callbacks and priorities |
When diagnosing PHP errors, WordPress debugging can be enabled temporarily in a controlled environment. On a public website, errors should be logged rather than displayed to visitors, and logs must be protected against unauthorised access.
The WP_DEBUG, WP_DEBUG_LOG and WP_DEBUG_DISPLAY constants are configured in wp-config.php, before WordPress finishes loading its configuration.
Do not leave public error display enabled on a production website.
For changes that affect content access, user permissions, redirects or database operations, confirm behaviour using accounts with different capabilities. A function that appears correct when tested as an administrator may behave differently for an editor, author, subscriber or anonymous visitor.
A small collection of well-maintained PHP snippets can provide useful custom functionality without requiring a large plugin development project. The important distinction is that these snippets remain executable code: they should be deployed selectively, checked for compatibility and reviewed whenever the underlying website changes.
