functions.php add_filter( 'use_block_editor_for_post', '__return_false', 10 );
add_filter( 'use_block_editor_for_post_type', '__return_false', 10 );
Keep in mind: The plugin also adds per-user and per-post editor switching, admin settings, and hooks for third-party plugins to control editor choice; the snippet only disables the block editor globally.
functions.php add_filter( 'post_row_actions', 'snippet_duplicate_post_link', 10, 2 );
add_filter( 'page_row_actions', 'snippet_duplicate_post_link', 10, 2 );
add_action( 'admin_action_duplicate_post_as_draft', 'snippet_duplicate_post_as_draft' );
function snippet_duplicate_post_link( $actions, $post ) {
if ( current_user_can( 'edit_posts' ) ) {
$url = wp_nonce_url(
admin_url( 'admin.php?action=duplicate_post_as_draft&post=' . $post->ID ),
'duplicate_post_' . $post->ID
);
$actions['duplicate'] = '<a href="' . esc_url( $url ) . '">Duplicate</a>';
}
return $actions;
}
function snippet_duplicate_post_as_draft() {
if ( empty( $_GET['post'] ) || ! isset( $_GET['_wpnonce'] ) ) {
wp_die( 'No post ID supplied.' );
}
$post_id = absint( $_GET['post'] );
check_admin_referer( 'duplicate_post_' . $post_id );
$post = get_post( $post_id );
if ( ! $post ) {
wp_die( 'Post not found.' );
}
$new_id = wp_insert_post( [
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_status' => 'draft',
'post_type' => $post->post_type,
'post_author' => get_current_user_id(),
'post_parent' => $post->post_parent,
'menu_order' => $post->menu_order,
] );
// Copy post meta.
foreach ( get_post_meta( $post_id ) as $key => $values ) {
foreach ( $values as $value ) {
add_post_meta( $new_id, $key, maybe_unserialize( $value ) );
}
}
wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
exit;
}
Classic Widgets Restore classic widgets screen, disable block widget editor. functions.php add_filter( 'use_widgets_block_editor', '__return_false' );
Keep in mind: The plugin also removes the block-based widget editor from the Customizer; add remove_theme_support( 'widgets-block-editor' ) if needed.
functions.php // Change this to your desired secret login slug
define( 'CUSTOM_LOGIN_SLUG', 'my-secret-login' );
add_action( 'init', function () {
$request = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$slug = CUSTOM_LOGIN_SLUG;
// Block direct access to wp-login.php and wp-admin (for non-logged-in users)
if ( preg_match( '#/wp-login\.php#', $request ) ) {
if ( ! isset( $_GET[ $slug ] ) && strpos( $_SERVER['REQUEST_URI'], $slug ) === false ) {
wp_redirect( home_url( '/' ) );
exit;
}
}
} );
add_filter( 'login_url', function ( $url ) {
return home_url( CUSTOM_LOGIN_SLUG );
}, 10 );
add_action( 'init', function () {
$slug = CUSTOM_LOGIN_SLUG;
$request = trim( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), '/' );
if ( $request === $slug ) {
require_once ABSPATH . 'wp-login.php';
exit;
}
} );
Keep in mind: The plugin provides a settings UI to configure the slug without editing code; this snippet requires hardcoding the slug directly.
Hello Dolly Display a random Hello Dolly lyric in the admin bar functions.php add_action( 'admin_notices', function () {
$lyrics = explode( "\n", "Hello, Dolly\nWell, hello, Dolly\nIt's so nice to have you back where you belong\nYou're lookin' swell, Dolly\nI can tell, Dolly\nYou're still glowin', you're still crowin'\nYou're still goin' strong" );
$lyric = $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ];
printf(
'<p id="dolly" style="float:right;margin:0;padding:10px 20px 0 0;font-style:italic;">%s</p>',
esc_html( $lyric )
);
} );
Keep in mind: The real plugin uses the full set of Hello Dolly lyrics; expand the string above to match.
functions.php add_filter( 'use_block_editor_for_post', '__return_false', 10 );
add_filter( 'use_widgets_block_editor', '__return_false' );
Keep in mind: The plugin also offers per-post-type, per-role, per-template, and per-ID granular control, plus UI tweaks like hiding the Gutenberg menu item and nag notices, which the snippet does not replicate.
functions.php add_action( 'wp_head', 'my_ga4_tracking_code' );
function my_ga4_tracking_code() {
$measurement_id = 'G-XXXXXXXXXX'; // Replace with your GA4 Measurement ID
?>
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $measurement_id ); ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<?php echo esc_js( $measurement_id ); ?>');
</script>
<?php
}
Keep in mind: The snippet does not skip tracking for logged-in admins, support IP anonymisation toggles, or provide a settings UI.
functions.php // Add your scripts/code to wp_head (header)
add_action( 'wp_head', function () {
?>
<!-- paste header code here, e.g. Google Analytics -->
<?php
} );
// Add your scripts/code just after <body> opens
add_action( 'wp_body_open', function () {
?>
<!-- paste body code here, e.g. GTM noscript -->
<?php
} );
// Add your scripts/code to wp_footer (footer)
add_action( 'wp_footer', function () {
?>
<!-- paste footer code here, e.g. Facebook Pixel -->
<?php
} );
Keep in mind: The plugin provides a settings UI so non-developers can paste code without touching files; the snippet requires direct file editing instead.
functions.php add_action( 'template_redirect', function () {
if ( is_404() ) {
wp_redirect( home_url( '/' ), 301 );
exit;
}
} );
Keep in mind: The plugin adds a settings UI and a log of captured 404 URLs; the snippet always redirects to the homepage with no configurable target.
functions.php add_filter( 'xmlrpc_enabled', '__return_false' );
functions.php // Add your global header code (wrap in <script> or <style> tags)
add_action( 'wp_head', function () {
echo "<!-- your header code here -->\n";
} );
// Add your global footer code
add_action( 'wp_footer', function () {
echo "<!-- your footer code here -->\n";
} );
Keep in mind: The plugin also provides a settings UI and per-post/page injection via meta boxes; those require extra code to replicate.
functions.php add_action( 'wp_head', function () {
$clarity_id = 'YOUR_CLARITY_PROJECT_ID';
?>
<script type="text/javascript">
(function(c,l,a,r,i,t,y){
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i;
y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
})(window, document, "clarity", "script", "<?php echo esc_js( $clarity_id ); ?>");
</script>
<?php
} );
Keep in mind: Replace YOUR_CLARITY_PROJECT_ID with your real project ID. The plugin also offers a settings UI and optional WooCommerce/consent integrations that this snippet does not replicate.
functions.php add_action( 'template_redirect', function () {
if ( ! is_404() ) {
return;
}
$custom_page_id = 42; // Replace with your 404 page ID.
$post = get_post( $custom_page_id );
if ( ! $post ) {
return;
}
// Keep the 404 status code; do not redirect.
status_header( 404 );
nocache_headers();
// Swap in the custom page and render it.
global $wp_query;
$wp_query->posts = array( $post );
$wp_query->post = $post;
$wp_query->post_count = 1;
$wp_query->found_posts = 1;
$wp_query->is_404 = false;
$wp_query->is_page = true;
$wp_query->is_singular = true;
include get_template_directory() . '/page.php';
exit;
} );
Keep in mind: The plugin also provides a settings UI, a Gutenberg block, and a shortcode for displaying the offending URL; those are not replicated here.
functions.php if ( isset( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https' ) {
$_SERVER['HTTPS'] = 'on';
}
Keep in mind: This line belongs in wp-config.php before the WordPress settings are loaded, not in functions.php.
functions.php add_action( 'wp_enqueue_scripts', function () {
global $wp_styles;
if ( empty( $wp_styles->queue ) ) {
return;
}
foreach ( $wp_styles->queue as $handle ) {
$src = $wp_styles->registered[ $handle ]->src ?? '';
if ( strpos( $src, 'fonts.googleapis.com' ) !== false ) {
wp_dequeue_style( $handle );
wp_deregister_style( $handle );
}
}
}, 100 );
// Also block Google Fonts added via @import in inline styles or editor blocks
add_filter( 'style_loader_tag', function ( $html, $handle ) {
if ( strpos( $html, 'fonts.googleapis.com' ) !== false ) {
return '';
}
return $html;
}, 10, 2 );
Keep in mind: The plugin also targets specific third-party plugins and includes an admin-bar checker tool, which this snippet does not replicate.
functions.php function encode_email_addresses( $content ) {
return preg_replace_callback(
'/[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/',
function ( $matches ) {
$encoded = '';
$chars = str_split( $matches[0] );
foreach ( $chars as $i => $char ) {
$encoded .= ( $i % 2 === 0 )
? '&#' . ord( $char ) . ';'
: '&#x' . dechex( ord( $char ) ) . ';';
}
return $encoded;
},
$content
);
}
foreach ( [ 'the_content', 'the_excerpt', 'widget_text', 'comment_text' ] as $filter ) {
add_filter( $filter, 'encode_email_addresses', 20 );
}
Keep in mind: The plugin also handles mailto links and provides a shortcode for encoding arbitrary text; those are not replicated here.
JavaScript document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll(
'.elementor-column[data-click-url], .elementor-section[data-click-url], .e-con[data-click-url]'
).forEach(function (el) {
var url = el.dataset.clickUrl;
if (!url) return;
el.style.cursor = 'pointer';
el.addEventListener('click', function (e) {
if (e.target.closest('a, button')) return;
var target = el.dataset.clickTarget || '_self';
window.open(url, target);
});
});
});
Keep in mind: This JS handles the click behaviour; you still need a small PHP snippet to add the custom control field inside the Elementor editor and output the data-click-url attribute on the rendered element.
functions.php // New user notification to admin
add_filter( 'wp_send_new_user_notification_to_admin', '__return_false' );
// New user notification to user
add_filter( 'wp_send_new_user_notification_to_user', '__return_false' );
// Password change notification to user
add_filter( 'send_password_change_email', '__return_false' );
// Password change notification to admin
add_filter( 'wp_password_change_notification_email', '__return_false' );
// Email address change notification to user
add_filter( 'send_email_change_email', '__return_false' );
// Forgotten password email to user/admin
add_filter( 'retrieve_password_notification_email', '__return_false' );
// Auto core update emails (suppress success-only; failures still send)
add_filter( 'auto_core_update_send_email', function( $send, $type ) {
return ( $type === 'success' ) ? false : $send;
}, 10, 2 );
// Auto plugin update emails
add_filter( 'auto_plugin_update_send_email', '__return_false' );
// Auto theme update emails
add_filter( 'auto_theme_update_send_email', '__return_false' );
// Comment moderation / post author notifications
add_filter( 'notify_post_author', '__return_false' );
add_filter( 'notify_moderator', '__return_false' );
Keep in mind: Comment out or remove any line for notifications you still want to send. The plugin's UI lets you toggle each one individually; this snippet disables all of them.
JavaScript // Save as smooth-scroll.js and enqueue it, or paste into a JS snippet plugin.
// Uses the native CSS scroll-behavior for a zero-dependency approach.
document.documentElement.style.scrollBehavior = 'smooth';
Keep in mind: The plugin likely bundles a dedicated library (e.g. SmoothScroll.js) with tunable speed and easing; this CSS-only approach uses the browser default easing and has no settings.
functions.php // Save a custom redirect URL via the post editor (add a meta box or use the CLI).
// This snippet reads the meta and redirects on the front end.
add_action( 'template_redirect', function () {
if ( ! is_singular() ) {
return;
}
$url = get_post_meta( get_the_ID(), '_page_links_to', true );
if ( $url ) {
wp_redirect( esc_url_raw( $url ), 301 );
exit;
}
} );
// Rewrite the permalink in nav menus and post loops to point to the custom URL.
add_filter( 'post_link', 'plt_custom_url', 10, 2 );
add_filter( 'page_link', 'plt_custom_url', 10, 2 );
add_filter( 'post_type_link', 'plt_custom_url', 10, 2 );
function plt_custom_url( $url, $post ) {
$custom = get_post_meta( is_object( $post ) ? $post->ID : $post, '_page_links_to', true );
return $custom ? esc_url( $custom ) : $url;
}
Keep in mind: This snippet has no settings UI for entering the URL; you would need to add a meta box or set the meta value manually.
functions.php add_action( 'admin_bar_menu', function( $wp_admin_bar ) {
if ( ! current_user_can( 'manage_options' ) || is_admin() ) {
return;
}
$template = get_single_template() ?: get_page_template() ?: get_index_template();
$file = $template ? basename( $template ) : 'unknown';
$theme = wp_get_theme()->get( 'Name' );
$wp_admin_bar->add_node( [
'id' => 'current-template',
'title' => '📄 ' . esc_html( $theme . ' › ' . $file ),
'href' => false,
] );
global $template as $tpl;
foreach ( get_included_files() as $f ) {
if ( strpos( $f, get_template_directory() ) === 0 ) {
$wp_admin_bar->add_node( [
'parent' => 'current-template',
'id' => 'tpl-' . md5( $f ),
'title' => esc_html( str_replace( get_template_directory() . '/', '', $f ) ),
] );
}
}
}, 100 );
Keep in mind: The included-files list uses get_included_files() as an approximation; the original plugin hooks earlier to capture only theme template parts more precisely.
functions.php add_action( 'wp_footer', function () {
$property_id = 'YOUR_PROPERTY_ID'; // e.g. 5b1234abc123456789012345
$widget_id = 'YOUR_WIDGET_ID'; // e.g. default
?>
<script type="text/javascript">
var Tawk_API = Tawk_API || {}, Tawk_LoadStart = new Date();
(function(){
var s1 = document.createElement("script"), s0 = document.getElementsByTagName("script")[0];
s1.async = true;
s1.src = 'https://embed.tawk.to/<?php echo esc_js( $property_id ); ?>/<?php echo esc_js( $widget_id ); ?>';
s1.charset = 'UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1, s0);
})();
</script>
<?php
} );
Keep in mind: The plugin also provides a settings page to enter your Property ID and toggle the widget per user role; replace the hardcoded IDs above with your own values.
functions.php add_action( 'wp_head', function () {
?>
<style>
body { user-select: none; -webkit-user-select: none; }
</style>
<script>
document.addEventListener( 'contextmenu', function(e) { e.preventDefault(); } );
document.addEventListener( 'copy', function(e) { e.preventDefault(); } );
document.addEventListener( 'cut', function(e) { e.preventDefault(); } );
document.addEventListener( 'keydown', function(e) {
if ( ( e.ctrlKey || e.metaKey ) && [ 'c', 'x', 'u', 's', 'a' ].includes( e.key.toLowerCase() ) ) {
e.preventDefault();
}
} );
</script>
<?php
} );
Keep in mind: The snippet does not replicate the Pro image-watermarking feature.
functions.php add_shortcode( 'my_php_snippet', function( $atts ) {
ob_start();
// Place your PHP code here
echo 'Hello from your snippet!';
return ob_get_clean();
} );
Keep in mind: The plugin provides a UI to manage multiple named snippets and a TinyMCE dropdown; the snippet requires one add_shortcode call per snippet instead.
functions.php // Redirect specific users, roles, or everyone after login.
add_filter( 'login_redirect', function ( $redirect_to, $requested_redirect_to, $user ) {
if ( is_wp_error( $user ) ) {
return $redirect_to;
}
// Redirect a specific user by username.
if ( $user->user_login === 'john' ) {
return home_url( '/dashboard/' );
}
// Redirect by role.
if ( in_array( 'editor', (array) $user->roles, true ) ) {
return admin_url( 'edit.php' );
}
// Blanket rule for everyone else.
return home_url( '/welcome/' );
}, 10, 3 );
// Optional: redirect after logout.
add_action( 'wp_logout', function () {
wp_safe_redirect( home_url( '/logged-out/' ) );
exit;
} );
Keep in mind: The plugin adds a settings UI, role/capability matrix, post-registration redirect, and dynamic placeholders that this snippet does not replicate.
functions.php add_action( 'template_redirect', function () {
if ( ! is_ssl() ) {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit;
}
} );
// Force SSL for admin and logins.
define( 'FORCE_SSL_ADMIN', true );
Keep in mind: The plugin also offers HSTS headers, mixed-content fixing, a dashboard SSL test tool, and an admin-bar widget which the snippet does not replicate.
CSS .entry-meta,
.post-meta,
.entry-date,
.byline,
.author,
.posted-on {
display: none !important;
}
Keep in mind: The PHP-based removal (filtering get_the_date, get_the_author, etc.) requires additional PHP hooks; the CSS above covers the frontend visual removal only.
functions.php add_shortcode( 'INSERT_ELEMENTOR', function( $atts ) {
$atts = shortcode_atts( [ 'id' => 0 ], $atts );
$id = absint( $atts['id'] );
if ( ! $id || ! class_exists( '\Elementor\Plugin' ) ) {
return '';
}
return \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $id, true );
} );
Keep in mind: The plugin also registers a custom post type for managing global templates; this snippet omits that CPT.
functions.php $cyr_to_lat = [
// Russian / Bulgarian
'а'=>'a','б'=>'b','в'=>'v','г'=>'g','д'=>'d','е'=>'e','ё'=>'yo',
'ж'=>'zh','з'=>'z','и'=>'i','й'=>'j','к'=>'k','л'=>'l','м'=>'m',
'н'=>'n','о'=>'o','п'=>'p','р'=>'r','с'=>'s','т'=>'t','у'=>'u',
'ф'=>'f','х'=>'kh','ц'=>'ts','ч'=>'ch','ш'=>'sh','щ'=>'shch',
'ъ'=>'','ы'=>'y','ь'=>'','э'=>'e','ю'=>'yu','я'=>'ya',
'А'=>'A','Б'=>'B','В'=>'V','Г'=>'G','Д'=>'D','Е'=>'E','Ё'=>'Yo',
'Ж'=>'Zh','З'=>'Z','И'=>'I','Й'=>'J','К'=>'K','Л'=>'L','М'=>'M',
'Н'=>'N','О'=>'O','П'=>'P','Р'=>'R','С'=>'S','Т'=>'T','У'=>'U',
'Ф'=>'F','Х'=>'Kh','Ц'=>'Ts','Ч'=>'Ch','Ш'=>'Sh','Щ'=>'Shch',
'Ъ'=>'','Ы'=>'Y','Ь'=>'','Э'=>'E','Ю'=>'Yu','Я'=>'Ya',
// Ukrainian extras
'і'=>'i','ї'=>'yi','є'=>'ye','ґ'=>'g',
'І'=>'I','Ї'=>'Yi','Є'=>'Ye','Ґ'=>'G',
];
$transliterate = function( $title ) use ( $cyr_to_lat ) {
return strtr( $title, $cyr_to_lat );
};
add_filter( 'sanitize_title', $transliterate, 9 );
add_filter( 'sanitize_file_name', $transliterate, 9 );
functions.php add_filter( 'wp_handle_upload', function ( $upload ) {
$max_width = 1920;
$max_height = 1080;
if ( ! isset( $upload['file'] ) || ! preg_match( '/\.(jpe?g|png|gif)$/i', $upload['file'] ) ) {
return $upload;
}
$editor = wp_get_image_editor( $upload['file'] );
if ( is_wp_error( $editor ) ) {
return $upload;
}
$size = $editor->get_size();
if ( $size['width'] > $max_width || $size['height'] > $max_height ) {
$editor->resize( $max_width, $max_height, false );
$editor->save( $upload['file'] );
}
return $upload;
} );
Keep in mind: The plugin also offers bulk rescaling of existing images and optional PNG to JPEG conversion, which this snippet does not cover.
functions.php add_action( 'template_redirect', function () {
if ( is_404() ) {
wp_redirect( home_url( '/' ), 301 );
exit;
}
} );
Keep in mind: This replicates the entire plugin; there are no settings to replicate.
iframe Register an iframe shortcode that outputs an iframe tag. functions.php add_shortcode( 'iframe', function( $atts ) {
$atts = shortcode_atts( [
'src' => 'https://www.youtube.com/embed/7_nAZQt9qu0',
'width' => '100%',
'height' => '500',
'scrolling' => 'yes',
'frameborder' => '0',
'class' => 'iframe-class',
], $atts, 'iframe' );
$known = [ 'src', 'width', 'height', 'scrolling', 'frameborder',
'marginheight', 'marginwidth', 'allowtransparency',
'id', 'class', 'style' ];
$html = '<iframe';
foreach ( $atts as $key => $value ) {
if ( $value === '' ) {
$html .= ' ' . esc_attr( $key ); // empty / boolean attribute
} else {
$html .= ' ' . esc_attr( $key ) . '="' . esc_attr( $value ) . '"';
}
}
$html .= '></iframe>';
return $html;
} );
Keep in mind: The same_height_as JS feature and dynamic height-matching are not replicated by this snippet.
functions.php add_action( 'template_redirect', function () {
ob_start( function ( $buffer ) {
$replacements = [
'Find this text' => 'Replace with this',
'Another old string' => 'Another new string',
];
return str_replace(
array_keys( $replacements ),
array_values( $replacements ),
$buffer
);
} );
} );
Keep in mind: The plugin provides a settings UI to manage pairs without code edits; this snippet requires hardcoding each find/replace pair.
functions.php add_action( 'init', function () {
$missed = get_posts( [
'post_status' => 'future',
'date_query' => [ [ 'column' => 'post_date', 'before' => 'now' ] ],
'posts_per_page' => -1,
'fields' => 'ids',
] );
foreach ( $missed as $post_id ) {
wp_publish_post( $post_id );
}
} );
Keep in mind: This runs on every front-end request; consider wrapping it in a transient lock to limit database queries on high-traffic sites.
SMTP Mailer Configure WordPress to send email via SMTP server functions.php add_action( 'phpmailer_init', function ( PHPMailer\PHPMailer\PHPMailer $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.gmail.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Username = '[email protected]';
$phpmailer->Password = 'your-password';
$phpmailer->SMTPSecure = 'tls';
$phpmailer->Port = 587;
$phpmailer->From = '[email protected]';
$phpmailer->FromName = 'Your Name';
} );
Keep in mind: Replace the credentials with your own values; the plugin also provides a settings UI, test email tool, and optional SSL verification toggle that this snippet omits.
functions.php add_action( 'wp_footer', function () {
if ( is_admin() || ( is_user_logged_in() && ! current_user_can( 'administrator' ) ) ) {
return;
}
$rules = [
'prerender' => [
[
'source' => 'document',
'where' => [ 'href_matches' => '/*' ],
'eagerness' => 'moderate',
],
],
];
printf(
'<script type="speculationrules">%s</script>',
wp_json_encode( $rules )
);
} );
Keep in mind: The plugin adds a settings UI, supports a no-prerender CSS class on links, and has a filter to exclude URL paths; those are not replicated here.
EasyMedia Increase WordPress upload size limit and execution time functions.php // Increase upload size, memory, and execution time limits.
@ini_set( 'upload_max_filesize', '256M' );
@ini_set( 'post_max_size', '256M' );
@ini_set( 'memory_limit', '256M' );
@ini_set( 'max_execution_time', '300' );
add_filter( 'upload_size_limit', function() {
return 256 * 1024 * 1024; // 256 MB in bytes
} );
Keep in mind: The role-based upload limits, system status dashboard, and file-type restrictions from the Pro version are not replicated here.
functions.php // Define the default featured image attachment ID.
define( 'DEFAULT_FEATURED_IMAGE_ID', 42 ); // Replace with your attachment ID.
add_filter( 'post_thumbnail_id', function( $thumbnail_id, $post ) {
if ( empty( $thumbnail_id ) ) {
return DEFAULT_FEATURED_IMAGE_ID;
}
return $thumbnail_id;
}, 10, 2 );
Keep in mind: Replace the attachment ID with your chosen image; the plugin stores this via a settings UI in the Media settings page.
functions.php add_action( 'init', function () {
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'tiny_mce_plugins', function ( $plugins ) {
return array_diff( (array) $plugins, [ 'wpemoji' ] );
} );
add_filter( 'wp_resource_hints', function ( $urls, $relation_type ) {
if ( 'dns-prefetch' === $relation_type ) {
$urls = array_diff( $urls, [ apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' ) ] );
}
return $urls;
}, 10, 2 );
} );
Keep in mind: The plugin's PSR-12 architecture and static analysis tooling are not replicated, but the full runtime behaviour is.
functions.php // Remove pingback methods from XML-RPC
add_filter( 'xmlrpc_methods', function( $methods ) {
unset( $methods['pingback.ping'] );
unset( $methods['pingback.extensions.getPingbacks'] );
return $methods;
} );
// Remove X-Pingback HTTP header
add_filter( 'wp_headers', function( $headers ) {
unset( $headers['X-Pingback'] );
return $headers;
} );
Keep in mind: This keeps the rest of XML-RPC functional, unlike fully disabling it.
functions.php // Add "Clone" row action to posts and pages
add_filter( 'post_row_actions', 'fpd_duplicate_row_action', 10, 2 );
add_filter( 'page_row_actions', 'fpd_duplicate_row_action', 10, 2 );
function fpd_duplicate_row_action( $actions, $post ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return $actions;
}
$url = wp_nonce_url(
add_query_arg(
[ 'action' => 'fpd_duplicate_post', 'post' => $post->ID ],
admin_url( 'admin.php' )
),
'fpd_duplicate_' . $post->ID
);
$actions['clone'] = '<a href="' . esc_url( $url ) . '">' . __( 'Clone' ) . '</a>';
return $actions;
}
// Handle the duplication
add_action( 'admin_action_fpd_duplicate_post', 'fpd_duplicate_post_handler' );
function fpd_duplicate_post_handler() {
$post_id = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0;
if ( ! $post_id || ! check_admin_referer( 'fpd_duplicate_' . $post_id ) ) {
wp_die( 'Invalid request.' );
}
$post = get_post( $post_id );
if ( ! $post || ! current_user_can( 'edit_post', $post_id ) ) {
wp_die( 'Permission denied.' );
}
$new_id = wp_insert_post( [
'post_title' => $post->post_title . ' (Copy)',
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_type' => $post->post_type,
'post_status' => 'draft',
'post_author' => get_current_user_id(),
] );
$redirect = ( $post->post_type === 'page' ) ? 'edit.php?post_type=page' : 'edit.php';
wp_redirect( admin_url( $redirect ) );
exit;
}
functions.php add_action( 'init', function () {
register_taxonomy_for_object_type( 'category', 'page' );
register_taxonomy_for_object_type( 'post_tag', 'page' );
} );
To Top Floating scroll-to-top button with smooth animation JavaScript // Add a scroll-to-top button via CSS + JS (enqueue from functions.php if preferred)
add_action( 'wp_footer', function () { ?>
<style>
#to-top {
position: fixed;
bottom: 2rem;
right: 2rem;
width: 44px;
height: 44px;
background: #333;
color: #fff;
font-size: 1.25rem;
border: none;
border-radius: 4px;
cursor: pointer;
display: none;
align-items: center;
justify-content: center;
z-index: 9999;
opacity: 0.8;
}
#to-top:hover { opacity: 1; }
</style>
<button id="to-top" aria-label="Back to top">⇧</button>
<script>
(function () {
var btn = document.getElementById('to-top');
window.addEventListener('scroll', function () {
btn.style.display = window.scrollY > 300 ? 'flex' : 'none';
});
btn.addEventListener('click', function () {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
}());
</script>
<?php } );
Keep in mind: The plugin's Customizer settings for colors, shape, image button, opacity, and hide-on-small-devices are not replicated here.
functions.php // --- Global custom CSS ---
add_action( 'wp_head', function () {
$css = get_option( 'my_global_custom_css', '' );
if ( $css ) {
echo '<style id="my-global-custom-css">' . wp_strip_all_tags( $css ) . '</style>';
}
} );
// --- Per-post/page custom CSS meta box ---
add_action( 'add_meta_boxes', function () {
add_meta_box( 'my_custom_css', 'Custom CSS', function ( $post ) {
$css = get_post_meta( $post->ID, '_custom_css', true );
wp_nonce_field( 'my_custom_css_nonce', 'my_custom_css_nonce' );
echo '<textarea name="my_custom_css" rows="8" style="width:100%;">' . esc_textarea( $css ) . '</textarea>';
}, get_post_types( [ 'public' => true ] ), 'normal' );
} );
add_action( 'save_post', function ( $post_id ) {
if (
! isset( $_POST['my_custom_css_nonce'] ) ||
! wp_verify_nonce( $_POST['my_custom_css_nonce'], 'my_custom_css_nonce' ) ||
defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE
) return;
update_post_meta( $post_id, '_custom_css', wp_strip_all_tags( $_POST['my_custom_css'] ?? '' ) );
} );
add_action( 'wp_head', function () {
if ( ! is_singular() ) return;
$css = get_post_meta( get_the_ID(), '_custom_css', true );
if ( $css ) {
echo '<style id="my-post-custom-css">' . wp_strip_all_tags( $css ) . '</style>';
}
} );
Keep in mind: The plugin's settings page for managing global CSS and choosing the CSS output method is not replicated; global CSS must be set directly via the database or a wp-admin options page you build yourself.
functions.php // Add "Duplicate" row action to posts and pages
add_filter( 'post_row_actions', 'snippet_duplicate_post_link', 10, 2 );
add_filter( 'page_row_actions', 'snippet_duplicate_post_link', 10, 2 );
function snippet_duplicate_post_link( $actions, $post ) {
if ( ! current_user_can( 'edit_posts' ) ) {
return $actions;
}
$url = wp_nonce_url(
add_query_arg(
[ 'action' => 'snippet_duplicate_post', 'post' => $post->ID ],
admin_url( 'admin.php' )
),
'snippet_duplicate_post_' . $post->ID
);
$actions['duplicate'] = '<a href="' . esc_url( $url ) . '">Duplicate</a>';
return $actions;
}
// Handle the duplication
add_action( 'admin_action_snippet_duplicate_post', 'snippet_duplicate_post_handler' );
function snippet_duplicate_post_handler() {
if ( empty( $_GET['post'] ) ) {
wp_die( 'No post specified.' );
}
$post_id = absint( $_GET['post'] );
check_admin_referer( 'snippet_duplicate_post_' . $post_id );
$post = get_post( $post_id );
if ( ! $post ) {
wp_die( 'Post not found.' );
}
$new_id = wp_insert_post( [
'post_title' => $post->post_title . ' (Copy)',
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_status' => 'draft',
'post_type' => $post->post_type,
'post_author' => get_current_user_id(),
] );
// Copy post meta
foreach ( get_post_meta( $post_id ) as $key => $values ) {
foreach ( $values as $value ) {
add_post_meta( $new_id, $key, maybe_unserialize( $value ) );
}
}
wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
exit;
}
functions.php // Hide Add to Cart buttons
add_filter( 'woocommerce_is_purchasable', '__return_false' );
// Remove Add to Cart button on single product pages
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
// Remove Add to Cart button on loop/archive pages
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
// Redirect cart and checkout pages to shop
add_action( 'template_redirect', function () {
if ( is_cart() || is_checkout() ) {
wp_safe_redirect( wc_get_page_permalink( 'shop' ) );
exit;
}
} );
Keep in mind: The snippet applies catalog mode to all users and products globally; the premium per-product, per-category, and per-user-role targeting is not included.
functions.php add_filter( 'pre_update_option_new_admin_email', fn( $value ) => $value );
add_filter( 'pre_update_option_admin_email', fn( $value ) => $value );
// Bypass the pending email confirmation flow introduced in WP 4.9.
add_filter( 'pre_option_new_admin_email', '__return_false' );
Keep in mind: The plugin also offers a third-party test email service; the snippet skips that entirely.
functions.php add_filter( 'mce_buttons', function( $buttons ) {
// Add underline and justify buttons to the first TinyMCE toolbar row
$buttons[] = 'underline';
$buttons[] = 'justifyfull';
return $buttons;
} );
Keep in mind: The plugin also offers a settings page with three toolbar style options; this snippet always applies the full underline and justify option.
functions.php // Remove the /category/ base from category URLs.
add_filter( 'category_rewrite_rules', function ( $rules ) {
$new_rules = array();
foreach ( $rules as $pattern => $rewrite ) {
$new_rules[ str_replace( 'category/', '', $pattern ) ] = $rewrite;
}
return $new_rules;
} );
add_filter( 'category_link', function ( $link ) {
return str_replace( '/category/', '/', $link );
} );
// Flush rewrite rules once on activation.
register_activation_hook( __FILE__, function () {
flush_rewrite_rules();
} );
Keep in mind: The snippet does not handle 301 redirects from old /category/ URLs to the new structure; add a redirect rule separately if needed.
Search Exclude Exclude specific posts or pages from WordPress search results functions.php // Save the "exclude from search" checkbox on the post edit screen
add_action( 'post_submitbox_misc_actions', function () {
global $post;
$excluded = get_post_meta( $post->ID, '_search_exclude', true );
wp_nonce_field( 'search_exclude_nonce', 'search_exclude_nonce' );
echo '<div class="misc-pub-section">';
echo '<label><input type="checkbox" name="search_exclude" value="1"' . checked( $excluded, '1', false ) . '> Exclude from search results</label>';
echo '</div>';
} );
add_action( 'save_post', function ( $post_id ) {
if ( ! isset( $_POST['search_exclude_nonce'] ) || ! wp_verify_nonce( $_POST['search_exclude_nonce'], 'search_exclude_nonce' ) ) return;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( ! empty( $_POST['search_exclude'] ) ) {
update_post_meta( $post_id, '_search_exclude', '1' );
} else {
delete_post_meta( $post_id, '_search_exclude' );
}
} );
// Filter excluded posts out of search queries
add_action( 'pre_get_posts', function ( $query ) {
if ( ! $query->is_search() || is_admin() ) return;
$excluded = get_posts( [
'post_type' => 'any',
'meta_key' => '_search_exclude',
'meta_value' => '1',
'fields' => 'ids',
'numberposts' => -1,
] );
if ( ! empty( $excluded ) ) {
$query->set( 'post__not_in', array_merge( (array) $query->get( 'post__not_in' ), $excluded ) );
}
} );
Keep in mind: The plugin's settings page listing all excluded items and bulk/quick edit support are not replicated here.
Orphans Replace spaces after short words with non-breaking spaces functions.php add_filter( 'the_content', 'fix_typographic_orphans' );
add_filter( 'the_excerpt', 'fix_typographic_orphans' );
function fix_typographic_orphans( string $content ): string {
// Words treated as orphans (single letters common in Polish/Czech plus short conjunctions).
$orphans = apply_filters( 'orphans_list', array( 'a', 'i', 'o', 'u', 'w', 'z', 'że', 'by', 'do', 'na', 'od', 'po', 'we', 'ze' ) );
foreach ( $orphans as $word ) {
$pattern = '/(\s)(' . preg_quote( $word, '/' ) . ')(\s)/iu';
$replacement = '$1$2 ';
$content = preg_replace( $pattern, $replacement, $content );
}
return $content;
}
Keep in mind: The plugin also supports page builders like Bricks, Divi, and ACF fields; this snippet only covers standard post content and excerpts.
Simple Banner Display a simple announcement banner at the top of the site functions.php add_action( 'wp_body_open', 'simple_banner_output' );
function simple_banner_output() {
$message = 'Your announcement text here.';
$bg_color = '#f5a623';
$text_color = '#ffffff';
echo '<div style="width:100%;background-color:' . esc_attr( $bg_color ) . ';color:' . esc_attr( $text_color ) . ';text-align:center;padding:10px;z-index:9999;">'
. wp_kses_post( $message )
. '</div>';
}
Keep in mind: The plugin adds a settings UI, live preview, and multi-banner scheduling; the snippet hard-codes a single banner.
functions.php add_action( 'pre_get_posts', function ( WP_Query $query ) {
if ( is_admin() ) {
return;
}
// IDs of categories to exclude.
$excluded = array( 5, 12, 34 );
if (
$query->is_main_query() &&
( $query->is_home() || $query->is_archive() || $query->is_search() || $query->is_feed() )
) {
$query->set( 'category__not_in', $excluded );
}
} );
Keep in mind: Replace the IDs in $excluded with your own category IDs; the plugin provides a settings UI to pick categories without touching code.
Add MIME Types Allow additional MIME types and file extensions for upload functions.php add_filter( 'upload_mimes', function( $mimes ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['webp'] = 'image/webp';
$mimes['avif'] = 'image/avif';
$mimes['woff'] = 'font/woff';
$mimes['woff2'] = 'font/woff2';
return $mimes;
} );
Keep in mind: Add or remove entries to match the exact MIME types your site needs. SVG uploads carry XSS risk and should be sanitised before use.
WP Robots Txt Customize the dynamically generated WordPress robots.txt output functions.php add_filter( 'robots_txt', function( $output, $public ) {
return "User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n";
}, 10, 2 );
Keep in mind: Replace the return string with your desired robots.txt content; the plugin provides a settings UI on the Reading page to edit this without touching code.
functions.php add_filter( 'script_loader_src', function( $src ) {
if ( strpos( $src, 'maps.googleapis.com/maps/api/js' ) === false ) {
return $src;
}
$api_key = 'YOUR_GOOGLE_MAPS_API_KEY';
if ( strpos( $src, 'key=' ) === false ) {
$src = add_query_arg( 'key', $api_key, $src );
}
if ( strpos( $src, 'callback=' ) === false ) {
$src = add_query_arg( 'callback', 'Function.prototype', $src );
}
return $src;
}, 20 );
Keep in mind: Replace YOUR_GOOGLE_MAPS_API_KEY with your actual key. The plugin also provides a settings UI to store the key; this snippet hard-codes it instead.
functions.php // Disable the block editor
add_filter( 'use_block_editor_for_post', '__return_false' );
add_filter( 'use_widgets_block_editor', '__return_false' );
// Remove block styles from the frontend
add_action( 'wp_enqueue_scripts', function () {
wp_dequeue_style( 'wp-block-library' );
wp_dequeue_style( 'wp-block-library-theme' );
wp_dequeue_style( 'global-styles' );
wp_dequeue_style( 'classic-theme-styles' );
}, 20 );
// Remove block styles from the backend
add_action( 'enqueue_block_editor_assets', function () {
wp_dequeue_style( 'wp-edit-blocks' );
}, 20 );
// Remove WP patterns
add_action( 'init', function () {
remove_theme_support( 'core-block-patterns' );
} );
Keep in mind: The plugin also strips WooCommerce and WPML block styles; add matching wp_dequeue_style calls for those if needed.
functions.php add_filter( 'robots_txt', function( $output, $public ) {
$output = "User-agent: *\n";
$output .= "Disallow: /wp-admin/\n";
$output .= "Allow: /wp-admin/admin-ajax.php\n";
$output .= "Disallow: /wp-includes/\n";
$sitemap = home_url( '/sitemap.xml' );
if ( file_exists( ABSPATH . 'sitemap.xml' ) ) {
$output .= "Sitemap: $sitemap\n";
}
return $output;
}, 10, 2 );
Keep in mind: WordPress already generates a virtual robots.txt natively; this filter just customises its content.
Reveal IDs Show post, page, and media IDs in admin list tables functions.php // Add an ID column to posts, pages, and other post-type list tables
add_filter( 'manage_posts_columns', 'reveal_ids_add_column' );
add_filter( 'manage_pages_columns', 'reveal_ids_add_column' );
function reveal_ids_add_column( $columns ) {
$columns['reveal_id'] = 'ID';
return $columns;
}
add_action( 'manage_posts_custom_column', 'reveal_ids_render_column', 10, 2 );
add_action( 'manage_pages_custom_column', 'reveal_ids_render_column', 10, 2 );
function reveal_ids_render_column( $column, $post_id ) {
if ( 'reveal_id' === $column ) {
echo esc_html( $post_id );
}
}
// Add ID column to the Media library list view
add_filter( 'manage_media_columns', 'reveal_ids_add_column' );
add_action( 'manage_media_custom_column', 'reveal_ids_render_column', 10, 2 );
Keep in mind: The plugin also adds ID columns to taxonomy term and user list tables, which would need extra manage_{taxonomy}_columns and manage_users_columns filters to fully replicate.
Say What? Replace translatable strings from plugins, themes, or core functions.php add_filter( 'gettext', 'my_custom_string_replacements', 20, 3 );
add_filter( 'gettext_with_context', 'my_custom_string_replacements', 20, 3 );
function my_custom_string_replacements( $translated, $original, $domain ) {
$replacements = [
// 'text-domain' => [ 'Original string' => 'Replacement string' ],
'woocommerce' => [
'Add to cart' => 'Buy now',
],
'default' => [
'Howdy, %s' => 'Welcome, %s',
],
];
if ( isset( $replacements[ $domain ][ $original ] ) ) {
return $replacements[ $domain ][ $original ];
}
return $translated;
}
Keep in mind: The snippet requires hardcoded replacements; the plugin provides a database-driven UI and supports JS-rendered strings.
functions.php add_action( 'wp_footer', function () {
?>
<button id="back-to-top" aria-label="Back to top" style="
display:none;position:fixed;bottom:2rem;right:2rem;z-index:9999;
width:44px;height:44px;border-radius:50%;border:none;cursor:pointer;
background:#333;color:#fff;font-size:1.2rem;line-height:44px;text-align:center;">
⇧
</button>
<script>
(function(){
var btn = document.getElementById('back-to-top');
window.addEventListener('scroll', function(){
btn.style.display = window.scrollY > 300 ? 'block' : 'none';
});
btn.addEventListener('click', function(){
window.scrollTo({top:0, behavior:'smooth'});
});
})();
</script>
<?php
} );
Keep in mind: The snippet omits the scroll progress indicator, shape/color settings UI, responsive visibility controls, and icon library.
functions.php add_filter( 'wp_revisions_to_keep', function( $num, $post ) {
$limits = [
'post' => 10,
'page' => 5,
];
return isset( $limits[ $post->post_type ] ) ? $limits[ $post->post_type ] : $num;
}, 10, 2 );
Keep in mind: Adjust the $limits array per post type; the plugin adds a Settings Writing UI so non-developers can configure values without touching code.
functions.php add_filter( 'woocommerce_payment_complete_order_status', function( $status, $order_id, $order ) {
// Options: 'completed' for all paid orders, or check for virtual-only below.
if ( $order && $order->has_downloadable_item() ) {
return 'completed';
}
// Complete virtual-only orders.
$virtual_only = true;
foreach ( $order->get_items() as $item ) {
$product = $item->get_product();
if ( $product && ! $product->is_virtual() ) {
$virtual_only = false;
break;
}
}
return $virtual_only ? 'completed' : $status;
}, 10, 3 );
Keep in mind: This snippet covers virtual-only orders; change the return to always return 'completed' to auto-complete all paid orders regardless of product type.
functions.php add_filter( 'sanitize_file_name', function( $filename ) {
// Transliterate accented characters to ASCII equivalents
$filename = remove_accents( $filename );
// Separate name from extension
$ext = pathinfo( $filename, PATHINFO_EXTENSION );
$name = pathinfo( $filename, PATHINFO_FILENAME );
// Remove any characters that are not alphanumeric, dashes, or underscores
$name = strtolower( $name );
$name = preg_replace( '/[^a-z0-9\-_]/', '-', $name );
$name = preg_replace( '/-+/', '-', $name );
$name = trim( $name, '-' );
return $ext ? "{$name}.{$ext}" : $name;
} );
Keep in mind: The plugin adds a settings page to limit conversion to images only or all file types; this snippet always converts all uploaded files.
functions.php // Save a post meta flag to hide the featured image on singular views.
add_action( 'post_submitbox_misc_actions', function() {
global $post;
wp_nonce_field( 'hide_featured_image', 'hfi_nonce' );
$checked = get_post_meta( $post->ID, '_hide_featured_image', true );
echo '<div class="misc-pub-section"><label><input type="checkbox" name="hide_featured_image" value="1" ' . checked( $checked, '1', false ) . '> Hide featured image on singular view</label></div>';
} );
add_action( 'save_post', function( $post_id ) {
if ( ! isset( $_POST['hfi_nonce'] ) || ! wp_verify_nonce( $_POST['hfi_nonce'], 'hide_featured_image' ) ) return;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
update_post_meta( $post_id, '_hide_featured_image', isset( $_POST['hide_featured_image'] ) ? '1' : '' );
} );
// Filter out the thumbnail when the flag is set on a singular page/post.
add_filter( 'post_thumbnail_html', function( $html ) {
if ( is_singular() && in_the_loop() && get_post_meta( get_the_ID(), '_hide_featured_image', true ) === '1' ) {
return '';
}
return $html;
} );
Keep in mind: The snippet only hides the thumbnail inside the loop; themes loading it outside the loop need an additional check, and the block editor checkbox requires a separate JS/meta-box approach.
functions.php add_filter( 'wp_mail', '__return_false' );
Keep in mind: The plugin may also log or surface a notice when mail is blocked; the snippet silently drops all mail.
functions.php add_filter( 'rest_authentication_errors', function( $result ) {
if ( ! empty( $result ) ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_login_required',
__( 'REST API restricted to authenticated users.', 'text-domain' ),
array( 'status' => rest_authorization_required_code() )
);
}
return $result;
} );
Keep in mind: The plugin also strips REST headers and HTML head links for all users; add remove_action calls for rest_output_link_wp_head and wp_oembed_add_discovery_links if those are needed.
functions.php add_filter( 'upload_mimes', function( $mimes ) {
$mimes['svg'] = 'image/svg+xml';
$mimes['csv'] = 'text/csv';
$mimes['xml'] = 'text/xml';
$mimes['zip'] = 'application/zip';
$mimes['ai'] = 'application/postscript';
$mimes['mobi'] = 'application/x-mobipocket-ebook';
$mimes['dwg'] = 'application/acad';
// Add or remove entries as needed.
return $mimes;
} );
// Required in WordPress 5.1+ to pass the real MIME check.
add_filter( 'wp_check_filetype_and_ext', function( $data, $file, $filename, $mimes ) {
if ( ! $data['type'] ) {
$ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) );
$allowed = wp_get_mime_types();
if ( isset( $allowed[ $ext ] ) ) {
$data['ext'] = $ext;
$data['type'] = $allowed[ $ext ];
}
}
return $data;
}, 10, 4 );
Keep in mind: The snippet covers the core whitelist behaviour; the plugin also provides an admin UI for managing types without editing code.
functions.php // Register custom page templates
add_filter( 'theme_page_templates', function( $templates ) {
$templates['tpl-fullwidth.php'] = __( 'Full Width' );
$templates['tpl-blank.php'] = __( 'Blank' );
$templates['tpl-no-sidebar.php'] = __( 'No Sidebar' );
return $templates;
} );
// Serve the template files from the plugin/snippet folder
add_filter( 'template_include', function( $template ) {
$page_template = get_post_meta( get_the_ID(), '_wp_page_template', true );
$map = [
'tpl-fullwidth.php' => get_stylesheet_directory() . '/tpl-fullwidth.php',
'tpl-blank.php' => get_stylesheet_directory() . '/tpl-blank.php',
'tpl-no-sidebar.php' => get_stylesheet_directory() . '/tpl-no-sidebar.php',
];
if ( isset( $map[ $page_template ] ) && file_exists( $map[ $page_template ] ) ) {
return $map[ $page_template ];
}
return $template;
} );
Keep in mind: You still need to create the three template files in your theme; the snippet only handles registration and routing.
functions.php // Schedule the event on activation.
register_activation_hook( __FILE__, function () {
if ( ! wp_next_scheduled( 'publish_missed_scheduled_posts' ) ) {
wp_schedule_event( time(), 'every_15_minutes', 'publish_missed_scheduled_posts' );
}
} );
// Add a 15-minute interval.
add_filter( 'cron_schedules', function ( $schedules ) {
$schedules['every_15_minutes'] = [
'interval' => 900,
'display' => __( 'Every 15 Minutes' ),
];
return $schedules;
} );
// Publish any missed scheduled posts.
add_action( 'publish_missed_scheduled_posts', function () {
$missed = get_posts( [
'post_status' => 'future',
'date_query' => [ [ 'column' => 'post_date', 'before' => 'now' ] ],
'posts_per_page' => -1,
'post_type' => 'any',
] );
foreach ( $missed as $post ) {
wp_publish_post( $post->ID );
}
} );
// Clean up on deactivation.
register_deactivation_hook( __FILE__, function () {
wp_clear_scheduled_hook( 'publish_missed_scheduled_posts' );
} );
Keep in mind: Paste this into a must-use plugin file rather than functions.php so the activation and deactivation hooks fire correctly.
JavaScript document.addEventListener('DOMContentLoaded', function () {
var links = document.querySelectorAll('a[href]');
var host = window.location.hostname;
links.forEach(function (link) {
var href = link.getAttribute('href');
if (href && href.indexOf('://') !== -1 && href.indexOf(host) === -1) {
link.addEventListener('click', function (e) {
e.preventDefault();
window.open(href, '_blank');
});
}
});
});
Keep in mind: The plugin has settings for forced and ignored URL lists; this snippet opens every external link in a new tab with no exceptions.
functions.php add_action( 'admin_init', function () {
// Allow AJAX and CLI; change the capability and redirect URL to suit.
if ( wp_doing_ajax() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
$required_cap = 'edit_posts'; // e.g. 'manage_options' for admins only
$redirect_url = home_url( '/' );
if ( ! current_user_can( $required_cap ) ) {
wp_safe_redirect( $redirect_url );
exit;
}
} );
Keep in mind: The plugin also supports per-role redirects, allowed URL exceptions with wildcards, a custom login message, and optional AJAX blocking, none of which are replicated here.
functions.php add_filter( 'admin_footer_text', function( $text ) {
$ip = $_SERVER['SERVER_ADDR'] ?? 'N/A';
$php = phpversion();
$os = PHP_OS;
$mem_limit = ini_get( 'memory_limit' );
$wp_limit = WP_MEMORY_LIMIT;
$mem_used = memory_get_usage( true );
$mem_bytes = wp_convert_hr_to_bytes( $mem_limit );
$percent = $mem_bytes > 0 ? round( ( $mem_used / $mem_bytes ) * 100, 1 ) : 0;
$color = '';
if ( $percent >= 90 ) {
$color = 'color:red;';
} elseif ( $percent >= 75 ) {
$color = 'color:#f4a0a0;';
}
$used_mb = round( $mem_used / 1048576, 2 );
return sprintf(
'IP: <strong>%s</strong> | PHP: <strong>%s</strong> | OS: <strong>%s</strong> | Memory: <strong>%s MB</strong> / <strong>%s</strong> (<span style="%s"><strong>%s%%</strong></span>) | WP Limit: <strong>%s</strong>',
esc_html( $ip ), esc_html( $php ), esc_html( $os ),
$used_mb, esc_html( $mem_limit ),
esc_attr( $color ), $percent,
esc_html( $wp_limit )
);
} );
Keep in mind: The snippet does not include translation support or a settings screen.
functions.php add_action( 'template_redirect', function () {
if ( ! is_attachment() ) {
return;
}
$post = get_post();
$parent_id = $post ? $post->post_parent : 0;
$parent_post = $parent_id ? get_post( $parent_id ) : null;
if ( $parent_post && $parent_post->post_status === 'publish' ) {
// Parent exists and is published: 301 to parent post.
wp_redirect( get_permalink( $parent_post ), 301 );
exit;
} elseif ( ! $parent_post || $parent_post->post_status === 'trash' ) {
// Parent is trashed or never existed: 404 to avoid redirect loops.
global $wp_query;
$wp_query->set_404();
status_header( 404 );
return;
} else {
// Parent deleted from trash (no post record): 302 to home.
wp_redirect( home_url( '/' ), 302 );
exit;
}
} );
Keep in mind: The snippet treats a missing parent record as a 404 rather than a 302; adjust the else branch to wp_redirect home if you prefer the plugin's exact behaviour for fully deleted parents.
Catch IDs Show post, page, media, category, tag, and user IDs in admin tables functions.php // Add ID column to post/page/custom post type list tables
add_filter( 'manage_posts_columns', 'catch_ids_add_column' );
add_filter( 'manage_pages_columns', 'catch_ids_add_column' );
function catch_ids_add_column( $columns ) {
$columns['catch_id'] = 'ID';
return $columns;
}
add_action( 'manage_posts_custom_column', 'catch_ids_column_value', 10, 2 );
add_action( 'manage_pages_custom_column', 'catch_ids_column_value', 10, 2 );
function catch_ids_column_value( $column, $post_id ) {
if ( 'catch_id' === $column ) {
echo esc_html( $post_id );
}
}
// Add ID column to media library
add_filter( 'manage_media_columns', 'catch_ids_add_column' );
add_action( 'manage_media_custom_column', 'catch_ids_column_value', 10, 2 );
// Add ID column to taxonomy (category/tag) list tables
add_filter( 'manage_edit-category_columns', 'catch_ids_add_column' );
add_filter( 'manage_edit-post_tag_columns', 'catch_ids_add_column' );
add_filter( 'manage_category_custom_column', 'catch_ids_tax_value', 10, 3 );
add_filter( 'manage_post_tag_custom_column', 'catch_ids_tax_value', 10, 3 );
function catch_ids_tax_value( $out, $column, $term_id ) {
if ( 'catch_id' === $column ) {
return esc_html( $term_id );
}
return $out;
}
// Add ID column to users list table
add_filter( 'manage_users_columns', 'catch_ids_add_column' );
add_action( 'manage_users_custom_column', 'catch_ids_user_value', 10, 3 );
function catch_ids_user_value( $out, $column, $user_id ) {
if ( 'catch_id' === $column ) {
return esc_html( $user_id );
}
return $out;
}
functions.php add_shortcode( 'sc_embed_player', function( $atts ) {
$atts = shortcode_atts(
[
'fileurl' => '',
'autoplay' => 'no',
'loop' => 'no',
],
$atts,
'sc_embed_player'
);
if ( empty( $atts['fileurl'] ) ) {
return '';
}
$autoplay = ( $atts['autoplay'] === 'yes' ) ? ' autoplay' : '';
$loop = ( $atts['loop'] === 'yes' ) ? ' loop' : '';
$url = esc_url( $atts['fileurl'] );
return '<audio controls' . $autoplay . $loop . ' style="width:100%;">
<source src="' . $url . '">
Your browser does not support the audio element.
</audio>';
} );
Keep in mind: WordPress has a built-in audio shortcode and block that covers this use case with no extra code needed at all.
functions.php // Disable core, plugin, and theme update checks
add_filter( 'pre_option_update_core', '__return_null' );
add_filter( 'pre_option_update_plugins', '__return_null' );
add_filter( 'pre_option_update_themes', '__return_null' );
remove_action( 'wp_version_check', 'wp_version_check' );
remove_action( 'wp_update_plugins', 'wp_update_plugins' );
remove_action( 'wp_update_themes', 'wp_update_themes' );
add_filter( 'auto_update_core', '__return_false' );
add_filter( 'auto_update_plugin', '__return_false' );
add_filter( 'auto_update_theme', '__return_false' );
// Remove update nag and dashboard widget
remove_action( 'admin_notices', 'update_nag', 3 );
add_filter( 'site_transient_update_core', '__return_false' );
add_filter( 'site_transient_update_plugins', '__return_false' );
add_filter( 'site_transient_update_themes', '__return_false' );
Keep in mind: This snippet does not remove the Updates menu item from the admin dashboard; additional hooks are needed for that cosmetic detail.
Easy Hide Login Block wp-login.php unless a secret slug is present in the URL functions.php // Change 'my_secret_slug' to your chosen slug.
define( 'LOGIN_SLUG', 'my_secret_slug' );
add_action( 'init', function () {
if ( ! is_admin() ) {
$request = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
if ( strpos( $request, 'wp-login.php' ) !== false ) {
if ( empty( $_GET[ LOGIN_SLUG ] ) ) {
wp_redirect( home_url( '/' ) );
exit;
}
}
}
} );
Keep in mind: The slug is hardcoded as a constant; the plugin provides a settings screen to change it from the admin.
functions.php add_shortcode( 'evp_embed_video', function( $atts ) {
$a = shortcode_atts( [
'url' => '',
'poster' => '',
'width' => '100%',
'autoplay' => 'false',
'loop' => 'false',
'muted' => 'false',
'preload' => 'metadata',
], $atts );
if ( empty( $a['url'] ) ) {
return '';
}
$autoplay = filter_var( $a['autoplay'], FILTER_VALIDATE_BOOLEAN ) ? ' autoplay' : '';
$loop = filter_var( $a['loop'], FILTER_VALIDATE_BOOLEAN ) ? ' loop' : '';
$muted = filter_var( $a['muted'], FILTER_VALIDATE_BOOLEAN ) ? ' muted' : '';
$poster = $a['poster'] ? ' poster="' . esc_url( $a['poster'] ) . '"' : '';
$width = esc_attr( $a['width'] );
return sprintf(
'<video style="width:%s;height:auto;" controls preload="%s"%s%s%s%s><source src="%s" type="video/mp4"></video>',
$width,
esc_attr( $a['preload'] ),
$poster,
$autoplay,
$loop,
$muted,
esc_url( $a['url'] )
);
} );
Keep in mind: The snippet covers the core shortcode; the MediaElement skin, user-only videos, video schema, and right-click disable add-ons are not included.
functions.php add_shortcode( 'pdf', function( $atts ) {
$atts = shortcode_atts( [
'url' => '',
'width' => '100%',
'height' => '600px',
], $atts );
$url = esc_url( $atts['url'] );
if ( ! $url ) {
return '';
}
// Use Google Doc Viewer for Chrome / mobile, direct iframe otherwise.
$is_chrome = isset( $_SERVER['HTTP_USER_AGENT'] ) &&
str_contains( $_SERVER['HTTP_USER_AGENT'], 'Chrome' );
$src = $is_chrome
? 'https://docs.google.com/viewer?url=' . rawurlencode( $url ) . '&embedded=true'
: $url;
return sprintf(
'<iframe src="%s" width="%s" height="%s" style="border:none;"></iframe>',
esc_url( $src ),
esc_attr( $atts['width'] ),
esc_attr( $atts['height'] )
);
} );
Keep in mind: The plugin also registers a Gutenberg block and an oEmbed handler; this snippet covers only the shortcode approach.
Flying Pages Inject a prefetch/preload script for faster page navigation functions.php add_action( 'wp_footer', function () {
?>
<script>
(function () {
if (!window.IntersectionObserver) return;
const nav = navigator.connection;
if (nav && (nav.saveData || /2g/.test(nav.effectiveType))) return;
const prefetched = new Set();
function prefetch(url) {
if (prefetched.has(url)) return;
prefetched.add(url);
const link = document.createElement('link');
link.rel = 'prefetch';
link.href = url;
document.head.appendChild(link);
}
const queue = [];
let timer;
function enqueue(url) {
if (!prefetched.has(url)) queue.push(url);
if (!timer) timer = setInterval(() => {
const batch = queue.splice(0, 3);
batch.forEach(prefetch);
if (!queue.length) { clearInterval(timer); timer = null; }
}, 1000);
}
const observer = new IntersectionObserver(entries => {
entries.forEach(e => { if (e.isIntersecting) enqueue(e.target.href); });
});
requestIdleCallback(() => {
document.querySelectorAll('a[href^="<?php echo esc_js( home_url() ); ?>"]')
.forEach(a => observer.observe(a));
});
document.addEventListener('mouseover', e => {
const a = e.target.closest('a');
if (a && a.href.startsWith('<?php echo esc_js( home_url() ); ?>')) prefetch(a.href);
});
})();
</script>
<?php
}, 20 );
Keep in mind: The plugin ships a polished 1 KB production script with more edge-case handling; this snippet captures the core behaviour only.
functions.php // Remove the category base (e.g. /category/) from category URLs.
add_filter( 'category_base', '__return_empty_string' );
// Flush rewrite rules on activation / deactivation.
register_activation_hook( __FILE__, function () {
update_option( 'category_base', '' );
flush_rewrite_rules();
} );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
Keep in mind: Paste the first two lines into functions.php; the activation hooks only matter if packaging this as a plugin. You may also simply set Settings > Permalinks > Category base to a single space and save.
functions.php add_action( 'wp_enqueue_scripts', function () {
if ( ! is_singular() ) {
return;
}
$post = get_post();
if ( ! $post || ! has_blocks( $post->post_content ) ) {
return;
}
// Only load when the post contains a gallery or image block.
if ( ! has_block( 'core/gallery', $post ) && ! has_block( 'core/image', $post ) ) {
return;
}
// baguetteBox via CDN — swap for a local copy if preferred.
wp_enqueue_style(
'baguettebox',
'https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.11.1/baguetteBox.min.css',
[],
'1.11.1'
);
wp_enqueue_script(
'baguettebox',
'https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.11.1/baguetteBox.min.js',
[],
'1.11.1',
true
);
wp_add_inline_script( 'baguettebox', 'document.addEventListener("DOMContentLoaded",function(){baguetteBox.run(".wp-block-gallery,.wp-block-image");});' );
} );
Keep in mind: The snippet loads assets from a CDN; host the files locally for a fully self-contained solution. It does not cover Media and Text blocks or third-party gallery blocks without adding their selectors.
functions.php add_action( 'after_setup_theme', function () {
// Roles that should NOT see the admin bar.
$hidden_roles = [ 'subscriber', 'customer' ];
$user = wp_get_current_user();
if ( empty( $user->roles ) ) {
// Guest — hide the bar.
show_admin_bar( false );
return;
}
if ( array_intersect( $hidden_roles, $user->roles ) ) {
show_admin_bar( false );
}
} );
Keep in mind: Pro features such as device detection, page targeting, per-user overrides, time-based hiding, smart redirects, and inactivity auto-hide are not covered.
Hide Admin Bar Hide the WordPress admin bar for all or specific roles. functions.php add_action( 'after_setup_theme', function () {
// Hide admin bar for all users. To target a role, wrap in a current_user_can() check.
show_admin_bar( false );
} );
Keep in mind: The plugin adds per-role granularity via a settings screen; the snippet hides the bar for every user unless you add a current_user_can() condition.
CSS .entry-meta .author,
.entry-meta .posted-on {
display: none;
}
Keep in mind: Class names vary by theme; use PHP filters like the_author and the_date returning empty strings for a full removal approach instead.
functions.php add_action( 'wp_enqueue_scripts', function () {
wp_deregister_script( 'jquery' );
wp_deregister_script( 'jquery-core' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script(
'jquery-core',
'https://code.jquery.com/jquery-3.7.1.min.js',
[],
'3.7.1',
false
);
wp_register_script(
'jquery-migrate',
'https://code.jquery.com/jquery-migrate-3.4.1.min.js',
[ 'jquery-core' ],
'3.4.1',
false
);
wp_register_script( 'jquery', false, [ 'jquery-core', 'jquery-migrate' ], null, false );
} );
Keep in mind: Update the version numbers to whichever jQuery and jQuery Migrate releases you want to target.
LWS Hide Login Change the WordPress login URL and redirect old login paths functions.php // Set your desired login slug here
define( 'CUSTOM_LOGIN_SLUG', 'my-login' );
add_action( 'init', function () {
// Redirect wp-login.php and wp-admin (when not logged in) to 404
$request = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$request = trim( $request, '/' );
if ( $request === 'wp-login.php' || ( $request === 'wp-admin' && ! is_user_logged_in() ) ) {
wp_die( 'Not found.', 404 );
}
} );
add_filter( 'login_url', function ( $url ) {
return home_url( CUSTOM_LOGIN_SLUG );
}, 10, 1 );
add_action( 'parse_request', function ( $wp ) {
if ( trim( parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ), '/' ) === CUSTOM_LOGIN_SLUG ) {
require_once ABSPATH . 'wp-login.php';
exit;
}
} );
Keep in mind: The plugin adds a settings UI to configure the slug and custom redirect page without editing code.
functions.php add_action( 'wp_footer', function () {
$js = "document.addEventListener('contextmenu', function(e) {
if (e.target.tagName === 'IMG') {
e.preventDefault();
}
});";
// Optionally skip for logged-in users:
if ( ! is_user_logged_in() ) {
echo '<script>' . $js . '</script>';
}
} );
Keep in mind: The plugin has an option to allow right-click for logged-in users; the snippet hard-codes that behaviour but you can remove the is_user_logged_in check to always block.
functions.php add_action( 'init', function () {
register_taxonomy_for_object_type( 'category', 'page' );
register_taxonomy_for_object_type( 'post_tag', 'page' );
} );
Keep in mind: Pages will appear in standard category and tag archive queries; add the_category() or the_tags() to your template files to display them.
functions.php add_filter( 'the_content_feed', 'remove_powered_by_wordpress' );
add_filter( 'bloginfo', 'remove_powered_by_wordpress', 10, 2 );
function remove_powered_by_wordpress( $output, $show = '' ) {
return $output;
}
// Remove the credit text injected via footer action hooks in classic themes.
add_filter( 'twentyseventeen_credits', '__return_empty_string' );
// Universal approach: filter the footer credit string.
add_filter( 'get_bloginfo_rss', 'remove_powered_by_wordpress' );
// For most classic themes, simply replace the footer_credits output.
add_filter( 'twentytwentyone_credits', '__return_empty_string' );
add_filter( 'twentytwenty_credits', '__return_empty_string' );
// Catch-all: suppress the standard "Proudly powered by WordPress" string.
add_filter( 'site_info', function( $output ) {
return preg_replace( '/<a[^>]*>Proudly powered by WordPress<\/a>/i', '', $output );
} );
Keep in mind: The plugin also adds a replacement widget area in some themes and supports many third-party themes; the snippet only covers core classic themes.
JavaScript document.addEventListener('contextmenu', function(e) { e.preventDefault(); });
document.addEventListener('keydown', function(e) {
var blocked = [
e.ctrlKey && ['c','v','x','s','a','u','f','p','h','l','k','o'].includes(e.key.toLowerCase()),
[123, 114, 120, 117].includes(e.keyCode) // F12, F3, F6, F9
];
if (blocked.some(Boolean)) e.preventDefault();
});
document.addEventListener('selectstart', function(e) { e.preventDefault(); });
document.addEventListener('dragstart', function(e) { e.preventDefault(); });
document.addEventListener('copy', function(e) { e.preventDefault(); });
Keep in mind: The Pro features (IP blocking, country blocking, paywalls, watermarks, MailChimp integration) are not replicated by this snippet.
Tag Manager Inject custom code into header, body, and footer functions.php // Add your code to the <head> section
add_action( 'wp_head', function () {
?>
<!-- Your head code here, e.g. Google Analytics / GTM snippet -->
<?php
} );
// Add your code immediately after <body> opens
add_action( 'wp_body_open', function () {
?>
<!-- Your body-open code here, e.g. GTM noscript tag -->
<?php
} );
// Add your code just before </body>
add_action( 'wp_footer', function () {
?>
<!-- Your footer code here, e.g. Facebook Pixel, chat widget -->
<?php
} );
Keep in mind: The plugin also supports per-page and per-role exclusions, lazy loading, and multiple code blocks per section, which this snippet does not replicate.
functions.php add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
function hide_shipping_when_free_is_available( $rates, $package ) {
$free = array_filter( $rates, fn( $rate ) => 'free_shipping' === $rate->method_id );
if ( empty( $free ) ) {
return $rates;
}
// Keep local pickup alongside free shipping.
$keep = array_filter( $rates, fn( $rate ) => 'local_pickup' === $rate->method_id );
return $free + $keep;
}
Keep in mind: The plugin also has a settings UI to optionally keep local pickup and add extra allowed methods per zone; the snippet always keeps local pickup but does not replicate the extra-methods selector.
functions.php add_action( 'admin_head', function () {
if ( current_user_can( 'administrator' ) ) {
echo '<style>.notice, .notice-error, .notice-warning, .notice-success, .notice-info, .updated, .update-nag { display: none !important; }</style>';
}
} );
Keep in mind: The plugin also captures hidden notices and displays them in a dedicated Notifications Tab, which the snippet does not replicate.
Yandex Metrica Inject Yandex Metrica tracking counter script into page head functions.php add_action( 'wp_head', function () {
$counter_id = '12345678'; // Replace with your Yandex Metrica counter ID.
?>
<!-- Yandex.Metrika counter -->
<script type="text/javascript">
(function(m,e,t,r,i,k,a){m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");
ym(<?php echo esc_js( $counter_id ); ?>, "init", { clickmap:true, trackLinks:true, accurateTrackBounce:true });
</script>
<noscript><div><img src="https://mc.yandex.ru/watch/<?php echo esc_attr( $counter_id ); ?>" style="position:absolute; left:-9999px;" alt="" /></div></noscript>
<!-- /Yandex.Metrika counter -->
<?php
} );
Keep in mind: The plugin also offers role-based tracking exclusions and a dashboard widget showing Metrica stats, which this snippet does not replicate.
functions.php add_action( 'admin_head', function () {
$custom_css = '
/* Your custom admin CSS here */
#wpadminbar { background: #1d2327; }
';
echo '<style>' . $custom_css . '</style>';
} );
// To enqueue an external CSS file instead (or as well):
add_action( 'admin_enqueue_scripts', function () {
wp_enqueue_style( 'my-admin-css', 'https://example.com/path/to/admin.css' );
} );
Keep in mind: The plugin adds a settings UI so non-developers can paste CSS without touching code.
functions.php // Single product page
add_filter( 'woocommerce_product_single_add_to_cart_text', function( $text, $product ) {
switch ( $product->get_type() ) {
case 'simple': return 'Add to cart';
case 'external': return 'Buy product';
case 'grouped': return 'Add to cart';
case 'variable': return 'Add to cart';
}
return $text;
}, 10, 2 );
// Archive / shop pages
add_filter( 'woocommerce_product_add_to_cart_text', function( $text, $product ) {
switch ( $product->get_type() ) {
case 'simple': return 'Add to cart';
case 'external': return 'Buy product';
case 'grouped': return 'View products';
case 'variable': return 'Select options';
}
return $text;
}, 10, 2 );
Keep in mind: Replace the string values with your desired text. The snippet does not cover WooCommerce Bookings product types.
CDN Enabler Rewrite static asset URLs to a CDN hostname functions.php add_action( 'template_redirect', function () {
ob_start( function ( $html ) {
$site_url = get_option( 'siteurl' );
$cdn_url = 'https://cdn.example.com'; // replace with your CDN URL
// Rewrite URLs for common static file extensions.
return preg_replace(
'#' . preg_quote( $site_url, '#' ) . '(/[^"\']*\.(?:css|js|png|jpg|jpeg|gif|webp|svg|ico|woff2?|ttf|eot))#i',
$cdn_url . '$1',
$html
);
} );
} );
Keep in mind: The plugin also supports multisite, REST API responses, configurable include/exclude rules, and KeyCDN cache purging, which this snippet does not cover.
functions.php add_filter( 'post_row_actions', 'snippet_clone_post_link', 10, 2 );
add_filter( 'page_row_actions', 'snippet_clone_post_link', 10, 2 );
function snippet_clone_post_link( $actions, $post ) {
if ( current_user_can( 'edit_posts' ) ) {
$url = wp_nonce_url(
add_query_arg( [ 'action' => 'snippet_clone_post', 'post' => $post->ID ], admin_url( 'admin.php' ) ),
'snippet_clone_post_' . $post->ID
);
$actions['clone'] = '<a href="' . esc_url( $url ) . '">Clone</a>';
}
return $actions;
}
add_action( 'admin_action_snippet_clone_post', 'snippet_do_clone_post' );
function snippet_do_clone_post() {
$post_id = absint( $_GET['post'] ?? 0 );
check_admin_referer( 'snippet_clone_post_' . $post_id );
$post = get_post( $post_id );
if ( ! $post || ! current_user_can( 'edit_posts' ) ) {
wp_die( 'Not allowed.' );
}
$new_id = wp_insert_post( [
'post_title' => $post->post_title . ' (Copy)',
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_type' => $post->post_type,
'post_status' => 'draft',
'post_author' => get_current_user_id(),
] );
// Copy post meta.
foreach ( get_post_meta( $post_id ) as $key => $values ) {
foreach ( $values as $value ) {
add_post_meta( $new_id, $key, maybe_unserialize( $value ) );
}
}
wp_redirect( admin_url( 'edit.php?post_type=' . $post->post_type ) );
exit;
}
Cookie Bar Display a dismissable cookie consent bar at page bottom functions.php // Output the cookie bar HTML and JS
add_action( 'wp_footer', function () {
if ( isset( $_COOKIE['cookie_bar_accepted'] ) ) {
return;
}
?>
<div id="cookie-bar" style="position:fixed;bottom:0;left:0;right:0;background:#333;color:#fff;padding:12px 20px;text-align:center;z-index:9999;font-size:14px;">
This website uses cookies to ensure you get the best experience.
<button id="cookie-bar-accept" style="margin-left:12px;padding:4px 12px;cursor:pointer;">Accept</button>
</div>
<script>
document.getElementById('cookie-bar-accept').addEventListener('click', function () {
document.cookie = 'cookie_bar_accepted=1; path=/; max-age=' + (60*60*24*365);
document.getElementById('cookie-bar').style.display = 'none';
});
</script>
<?php
} );
Keep in mind: The plugin offers customizable message text, colors, and link to a privacy policy page via a settings UI which this snippet hardcodes.
functions.php // Replace YOUR_NUMBER with your WhatsApp number in international format (e.g. 15551234567)
define( 'MY_WHATSAPP_NUMBER', 'YOUR_NUMBER' );
add_action( 'wp_footer', 'my_whatsapp_button' );
function my_whatsapp_button() {
$url = 'https://wa.me/' . MY_WHATSAPP_NUMBER;
echo '<a href="' . esc_url( $url ) . '" target="_blank" rel="noopener noreferrer"
style="position:fixed;bottom:20px;right:20px;z-index:9999;background:#25d366;
color:#fff;border-radius:50%;width:56px;height:56px;display:flex;
align-items:center;justify-content:center;box-shadow:2px 2px 6px rgba(0,0,0,.3);
font-size:28px;text-decoration:none;" aria-label="Chat on WhatsApp">
💬
</a>';
}
Keep in mind: The snippet does not replicate the shortcode, page-visibility rules, or the WooCommerce and WPML integrations.
Custom Login Customize the WordPress login page logo and styles functions.php // Replace the login logo
add_filter( 'login_headerurl', fn() => home_url() );
add_filter( 'login_headertext', fn() => get_bloginfo( 'name' ) );
add_action( 'login_enqueue_scripts', function () {
?>
<style>
#login h1 a {
background-image: url('<?php echo esc_url( get_theme_file_uri( 'images/custom-logo.png' ) ); ?>');
background-size: contain;
width: 100%;
height: 80px;
}
body.login {
background-color: #f0f0f0;
}
</style>
<?php
} );
Keep in mind: The plugin offers a full settings UI with live preview, style packs, and premium extensions; the snippet only covers basic logo and colour changes.
functions.php add_action( 'wp_enqueue_scripts', function() {
if ( ! WC()->cart || WC()->cart->is_empty() ) {
wp_dequeue_script( 'wc-cart-fragments' );
}
}, 11 );
Keep in mind: The plugin re-enqueues cart fragments via a cookie check rather than a PHP cart check, which is more cache-friendly; this snippet uses a PHP-side check instead.
functions.php add_filter( 'wp_lazy_loading_enabled', '__return_false' );
functions.php add_action( 'template_redirect', function () {
if ( is_attachment() ) {
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
include get_query_template( '404' );
exit;
}
} );
// Rename new attachment slugs to their ID so they don't reserve pretty slugs.
add_filter( 'wp_insert_attachment_data', function ( $data ) {
$data['post_name'] = uniqid( 'attachment-' );
return $data;
} );
Keep in mind: The plugin also includes WP-CLI commands to bulk-mangle or restore existing attachment slugs, which the snippet does not cover.
functions.php add_filter( 'intermediate_image_sizes_advanced', function( $sizes ) {
unset(
$sizes['thumbnail'],
$sizes['medium'],
$sizes['medium_large'],
$sizes['large'],
$sizes['1536x1536'],
$sizes['2048x2048']
);
return $sizes;
} );
// Prevent WordPress from scaling down large originals.
add_filter( 'big_image_size_threshold', '__return_false' );
Keep in mind: Remove only the unset() lines for sizes you still want WordPress to generate.
functions.php // Hide update notifications in the admin
add_filter( 'site_transient_update_plugins', '__return_false' );
add_filter( 'site_transient_update_themes', '__return_false' );
add_filter( 'site_transient_update_core', '__return_false' );
// Remove the "updates" admin menu badge and dashboard widget
remove_action( 'admin_notices', 'update_nag', 3 );
add_filter( 'update_footer', '__return_empty_string', 11 );
// Disable auto-update email notifications for plugins and themes
add_filter( 'auto_plugin_update_send_email', '__return_false' );
add_filter( 'auto_theme_update_send_email', '__return_false' );
add_filter( 'send_core_update_notification_email', '__return_false' );
Keep in mind: The plugin exposes a settings screen to toggle each notification type individually; this snippet disables all of them at once.
functions.php add_action( 'admin_head', function () {
if ( ! current_user_can( 'manage_options' ) ) {
remove_all_actions( 'admin_notices' );
remove_all_actions( 'all_admin_notices' );
add_filter( 'site_transient_update_plugins', '__return_false' );
add_filter( 'site_transient_update_themes', '__return_false' );
}
} );
Keep in mind: This snippet hides notices and update signals from non-admins only; adjust the capability check or remove the condition to affect all users.
functions.php add_filter( 'wp_sitemaps_enabled', '__return_false' );
Keep in mind: This single filter also removes the sitemap entry from the virtual robots.txt, matching the plugin's full behaviour.
functions.php add_action( 'phpmailer_init', function ( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.elasticemail.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 2525;
$phpmailer->Username = 'YOUR_ELASTIC_EMAIL_ADDRESS';
$phpmailer->Password = 'YOUR_ELASTIC_EMAIL_SMTP_PASSWORD';
$phpmailer->SMTPSecure = 'tls';
} );
Keep in mind: This uses SMTP rather than the HTTP API; swap credentials and adjust port as needed for your account.
EMC Embed a Calendly scheduling page via shortcode functions.php add_shortcode( 'calendly', function( $atts ) {
$a = shortcode_atts( [
'url' => '',
'type' => '1', // 1 = inline, 2 = popup button
'text' => 'Schedule time with me',
'height' => '630',
], $atts );
if ( empty( $a['url'] ) ) {
return '';
}
$url = esc_url( $a['url'] );
// Enqueue Calendly widget script
wp_enqueue_script( 'calendly-widget', 'https://assets.calendly.com/assets/external/widget.js', [], null, true );
if ( '2' === $a['type'] ) {
// Popup button
wp_enqueue_style( 'calendly-widget-css', 'https://assets.calendly.com/assets/external/widget.css', [], null );
$text = esc_html( $a['text'] );
return "<a href=\"\" onclick=\"Calendly.initPopupWidget({url:'{$url}'});return false;\">{$text}</a>";
}
// Inline embed (default)
$height = absint( $a['height'] );
return "<div class=\"calendly-inline-widget\" data-url=\"{$url}\" style=\"min-width:320px;height:{$height}px;\"></div>";
} );
Keep in mind: The Pro features such as analytics, UTM passthrough, WooCommerce integration, reminders, and the visual widget customizer are not replicated.
JavaScript function equalizeHeights(selector, breakpoint) {
var $els = jQuery(selector);
if (breakpoint && jQuery(window).width() < breakpoint) {
$els.css('height', '');
return;
}
$els.css('height', '');
var max = 0;
$els.each(function () { max = Math.max(max, jQuery(this).outerHeight()); });
$els.css('height', max + 'px');
}
jQuery(function ($) {
var groups = [
{ selector: '.your-column-selector', breakpoint: 768 }
];
function runAll() {
groups.forEach(function (g) { equalizeHeights(g.selector, g.breakpoint); });
}
runAll();
$(window).on('resize orientationchange', runAll);
});
Keep in mind: Replace the groups array with your own selectors and breakpoints; the plugin's admin UI and PHP filter are not replicated.
functions.php add_shortcode( 'facebook-page-plugin', function( $atts ) {
$a = shortcode_atts( [
'href' => 'facebook',
'width' => '340',
'height' => '500',
'cover' => 'true',
'facepile' => 'true',
'tabs' => 'timeline',
'cta' => 'false',
'small' => 'false',
'adapt' => 'true',
'language' => get_locale(),
], $atts );
$hide_cover = $a['cover'] === 'true' ? 'false' : 'true';
$hide_cta = $a['cta'] === 'true' ? 'true' : 'false';
$small_header = $a['small'] === 'true' ? 'true' : 'false';
$adapt = $a['adapt'] === 'true' ? 'true' : 'false';
$url = 'https://www.facebook.com/' . esc_attr( $a['href'] );
return sprintf(
'<div class="fb-page" data-href="%s" data-width="%s" data-height="%s"
data-hide-cover="%s" data-show-facepile="%s" data-tabs="%s"
data-hide-cta="%s" data-small-header="%s" data-adapt-container-width="%s"></div>
<div id="fb-root"></div>
<script async defer src="https://connect.facebook.net/%s/sdk.js#xfbml=1&version=v19.0"></script>',
esc_url( $url ),
esc_attr( $a['width'] ),
esc_attr( $a['height'] ),
esc_attr( $hide_cover ),
esc_attr( $a['facepile'] ),
esc_attr( $a['tabs'] ),
esc_attr( $hide_cta ),
esc_attr( $small_header ),
esc_attr( $adapt ),
esc_attr( $a['language'] )
);
} );
functions.php add_action( 'wp_head', 'fathom_analytics_tracking_script' );
function fathom_analytics_tracking_script() {
$site_id = 'XXXXXXXX'; // Replace with your Fathom site ID
echo '<script src="https://cdn.usefathom.com/script.js" data-site="' . esc_attr( $site_id ) . '" defer></script>' . "\n";
}
Keep in mind: The plugin also adds an admin options page and lets you exclude tracking by user role; the snippet tracks all visitors unconditionally.
flowpaper Embed a PDF flipbook viewer via shortcode functions.php add_shortcode( 'flipbook', function( $atts ) {
$a = shortcode_atts( [
'pdf' => '',
'width' => '100%',
'height' => '600px',
'theme' => 'dark',
'title' => '',
'header' => 'Loading viewer',
'lightbox' => 'false',
'cover' => '',
], $atts );
if ( empty( $a['pdf'] ) ) {
return '';
}
$pdf = esc_url( $a['pdf'] );
$w = esc_attr( $a['width'] );
$h = esc_attr( $a['height'] );
$theme = esc_attr( $a['theme'] );
$title = esc_attr( $a['title'] );
return sprintf(
'<iframe src="https://online.flowpaper.com/embed/?pdf=%s&theme=%s&title=%s" width="%s" height="%s" style="border:none;" allowfullscreen></iframe>',
rawurlencode( $pdf ), $theme, $title, $w, $h
);
} );
Keep in mind: This uses FlowPaper's hosted embed URL; the real plugin loads its own JS viewer locally and supports lightbox, cover image, and branding options that would need extra work to replicate.
functions.php // Add a hidden honeypot field to the comment form via JS
add_action( 'comment_form', function () {
echo "<script>
var f = document.getElementById('commentform');
if (f) {
var i = document.createElement('input');
i.type = 'text'; i.name = 'hp_name'; i.value = '';
i.style.cssText = 'display:none!important';
f.appendChild(i);
}
</script>";
} );
// Reject the comment if the honeypot field is filled in
add_filter( 'preprocess_comment', function ( $data ) {
if ( ! empty( $_POST['hp_name'] ) ) {
wp_die( 'Spam detected.', 'Spam', [ 'response' => 403, 'back_link' => true ] );
}
return $data;
} );
Keep in mind: The snippet covers only the standard WordPress comment form, matching the plugin scope.
functions.php add_shortcode( 'html_sitemap', function( $atts ) {
$atts = shortcode_atts( [
'depth' => 0,
'child_of' => 0,
'exclude' => '',
'include' => '',
'sort_column'=> 'menu_order, post_title',
'sort_order' => 'ASC',
'post_type' => 'page',
'post_status'=> 'publish',
'class' => 'html-sitemap',
'id' => '',
], $atts, 'html_sitemap' );
$pages = wp_list_pages( [
'title_li' => '',
'echo' => false,
'depth' => (int) $atts['depth'],
'child_of' => (int) $atts['child_of'],
'exclude' => sanitize_text_field( $atts['exclude'] ),
'include' => sanitize_text_field( $atts['include'] ),
'sort_column' => sanitize_text_field( $atts['sort_column'] ),
'sort_order' => sanitize_text_field( $atts['sort_order'] ),
'post_type' => sanitize_key( $atts['post_type'] ),
'post_status' => sanitize_text_field( $atts['post_status'] ),
] );
if ( ! $pages ) {
return '';
}
$id = $atts['id'] ? ' id="' . esc_attr( $atts['id'] ) . '"' : '';
$class = $atts['class'] ? ' class="' . esc_attr( $atts['class'] ) . '"' : '';
return '<ul' . $id . $class . '>' . $pages . '</ul>';
} );
Keep in mind: The Gutenberg block, ordered list type, show_date, and several other advanced attributes are not replicated here.
JavaScript // Enqueue the script via functions.php
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'smooth-scroll-top',
get_template_directory_uri() . '/js/smooth-scroll.js',
[ 'jquery' ],
'1.0',
true
);
} );
// Or inline the behaviour directly:
add_action( 'wp_footer', function () { ?>
<style>
#scroll-to-top{position:fixed;bottom:30px;right:30px;display:none;cursor:pointer;background:#333;color:#fff;padding:10px 14px;border-radius:4px;z-index:9999}
</style>
<div id="scroll-to-top">⇧</div>
<script>
(function($){
$(window).on('scroll', function(){
$('#scroll-to-top').toggle($(this).scrollTop() > 300);
});
$('#scroll-to-top').on('click', function(){
$('html,body').animate({scrollTop:0}, 600);
});
$('a[href^="#"]').not('[href="#"]').on('click', function(e){
var target = $(this.hash);
if(!target.length) return;
e.preventDefault();
$('html,body').animate({scrollTop: target.offset().top}, 600);
});
})(jQuery);
</script>
<?php } );
Keep in mind: The snippet does not replicate RTL support or the jQuery UI easing effects included in the plugin.
functions.php add_action( 'add_meta_boxes', function () {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$post_types = get_post_types( [ 'public' => true ] );
foreach ( $post_types as $post_type ) {
add_meta_box(
'post-metadata-inspector',
'Post Metadata',
function ( WP_Post $post ) {
$meta = get_post_meta( $post->ID );
if ( empty( $meta ) ) {
echo '<p>No metadata found.</p>';
return;
}
echo '<table style="width:100%;border-collapse:collapse">';
echo '<tr><th style="text-align:left;padding:4px 8px">Key</th><th style="text-align:left;padding:4px 8px">Value</th></tr>';
foreach ( $meta as $key => $values ) {
$value = implode( ', ', array_map( function ( $v ) {
return esc_html( print_r( maybe_unserialize( $v ), true ) );
}, $values ) );
echo '<tr><td style="padding:4px 8px;vertical-align:top"><code>' . esc_html( $key ) . '</code></td><td style="padding:4px 8px">' . $value . '</td></tr>';
}
echo '</table>';
},
$post_type,
'normal',
'low'
);
}
} );
Keep in mind: The plugin also offers delete-meta buttons and developer filters for excluding keys; this snippet is read-only and has no filtering hooks.
JavaScript document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.elementor-section[data-wrapper-link], .elementor-column[data-wrapper-link]').forEach(function (el) {
var linkData = JSON.parse(el.dataset.wrapperLink);
if (!linkData || !linkData.url) return;
el.style.cursor = 'pointer';
el.addEventListener('click', function (e) {
if (e.target.closest('a, button, input, select, textarea')) return;
if (linkData.is_external) {
window.open(linkData.url, '_blank', linkData.nofollow ? 'noopener noreferrer' : 'noopener');
} else {
window.location.href = linkData.url;
}
});
});
});
Keep in mind: This relies on Elementor's native wrapper link data attribute, which Elementor already supports natively in modern versions, making the plugin potentially unnecessary altogether.
Minify HTML Minify HTML output by removing whitespace via output buffering functions.php add_action( 'template_redirect', function () {
ob_start( function ( $html ) {
// Preserve content inside <pre>, <textarea>, and <script>/<style> blocks
$html = preg_replace( '/<!--(?!\[if).*?-->/s', '', $html ); // strip HTML comments
$html = preg_replace( '/\s+/', ' ', $html ); // collapse whitespace
$html = preg_replace( '/>\s+</', '><', $html ); // remove space between tags
return trim( $html );
} );
} );
Keep in mind: The full plugin also minifies inline CSS and JS, removes XHTML void-element closing tags, and strips relative schemes from URLs; those extras are not replicated here.
functions.php add_action( 'login_enqueue_scripts', function () {
$logo_url = get_stylesheet_directory_uri() . '/images/login-logo.png';
$width = 200; // px
$height = 80; // px
?>
<style>
#login h1 a, .login h1 a {
background-image: url('<?php echo esc_url( $logo_url ); ?>');
background-size: contain;
width: <?php echo absint( $width ); ?>px;
height: <?php echo absint( $height ); ?>px;
}
</style>
<?php
} );
add_filter( 'login_headerurl', fn() => home_url() );
add_filter( 'login_headertext', fn() => get_bloginfo( 'name' ) );
Keep in mind: The custom message below the form and fade-in animation effects are not replicated by this snippet.
No Self Ping Prevent WordPress from sending self-pings on new posts. functions.php add_action( 'pre_ping', function ( &$links ) {
$home = home_url();
foreach ( $links as $key => $link ) {
if ( str_starts_with( $link, $home ) ) {
unset( $links[ $key ] );
}
}
} );
Keep in mind: The plugin also adds a settings field to exclude additional custom domains; the snippet only blocks the current site.
One Click SSL Redirect all traffic to HTTPS and fix mixed content URLs. functions.php // Force HTTPS redirect for all non-SSL requests.
add_action( 'template_redirect', function () {
if ( ! is_ssl() ) {
wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301 );
exit;
}
} );
// Rewrite all HTTP resource URLs to HTTPS in the page output.
add_filter( 'wp_content_url', 'set_url_scheme' );
add_filter( 'plugins_url', 'set_url_scheme' );
add_filter( 'theme_root_uri', 'set_url_scheme' );
add_filter( 'stylesheet_uri', 'set_url_scheme' );
add_filter( 'template_directory_uri', 'set_url_scheme' );
add_filter( 'the_content', function ( $content ) {
return str_replace( 'http://' . $_SERVER['HTTP_HOST'], 'https://' . $_SERVER['HTTP_HOST'], $content );
} );
Keep in mind: The plugin's setup wizard checks server SSL support before enabling; the snippet assumes SSL is already working. Also set WordPress and Site URL to https in Settings > General, or define them in wp-config.php, for full coverage.
Open Graph Insert Open Graph meta tags into WordPress post and page heads. functions.php add_action( 'wp_head', function () {
if ( ! is_singular() ) {
return;
}
$post = get_queried_object();
$title = get_the_title( $post );
$url = get_permalink( $post );
$desc = has_excerpt( $post ) ? get_the_excerpt( $post ) : wp_trim_words( get_the_content( null, false, $post ), 55 );
$image = get_the_post_thumbnail_url( $post, 'large' );
$site_name = get_bloginfo( 'name' );
echo '<meta property="og:type" content="article" />' . "\n";
echo '<meta property="og:title" content="' . esc_attr( $title ) . '" />' . "\n";
echo '<meta property="og:url" content="' . esc_url( $url ) . '" />' . "\n";
echo '<meta property="og:description" content="' . esc_attr( $desc ) . '" />' . "\n";
echo '<meta property="og:site_name" content="' . esc_attr( $site_name ) . '" />' . "\n";
if ( $image ) {
echo '<meta property="og:image" content="' . esc_url( $image ) . '" />' . "\n";
}
} );
Keep in mind: This covers singular posts and pages only; the plugin also handles archives, home pages, and provides a filter-based extension API for other plugins to override tags.
JavaScript // Enqueue Pinterest's own "Pin It" widget script
add_action( 'wp_enqueue_scripts', function () {
wp_enqueue_script(
'pinterest-pinit',
'https://assets.pinterest.com/js/pinit.js',
[],
null,
true
);
} );
// Wrap every post/page image with a Pinterest "Pin It" overlay
add_filter( 'the_content', function ( $content ) {
return preg_replace(
'/<img([^>]+src=["\']([^"\']+)["\'][^>]*)>/i',
'<span style="position:relative;display:inline-block;">$0'
. '<a href="https://pinterest.com/pin/create/button/?url=' . urlencode( get_permalink() )
. '&media=$2&description=" '
. 'data-pin-do="buttonPin" data-pin-count="beside" '
. 'style="position:absolute;top:4px;left:4px;display:none;" '
. 'class="pin-it-btn" target="_blank">'
. '<img src="https://assets.pinterest.com/images/pidgets/pinit_fg_en_rect_gray_20.png" /></a>'
. '</span>',
$content
);
} );
// CSS: show the button on image hover
add_action( 'wp_head', function () {
echo '<style>
span:hover > .pin-it-btn { display:inline-block !important; }
</style>';
} );
Keep in mind: The plugin also offers per-post/page toggle settings and a customisable button size; this snippet applies the button globally to all content images.
functions.php add_action( 'wp_head', function () {
$domain = 'yourdomain.com'; // replace with your site domain
echo '<script defer data-domain="' . esc_attr( $domain ) . '" src="https://plausible.io/js/script.js"></script>' . "\n";
} );
Keep in mind: The plugin also adds admin dashboard settings, a stats embed page, and optional outbound-link / custom-event tracking variants of the script.
functions.php add_filter( 'style_loader_src', 'bust_asset_cache' );
add_filter( 'script_loader_src', 'bust_asset_cache' );
function bust_asset_cache( $src ) {
if ( is_admin() ) {
return $src;
}
return add_query_arg( 'bust', time(), $src );
}
Keep in mind: Using time() busts the cache on every page load; replace with a fixed string or a stored option when you want a single manual-bump workflow.
functions.php add_action( 'wp_footer', function () {
?>
<script>
var refTagger = {
settings: {
bibleVersion: 'ESV',
addLogosLink: false,
tooltips: { enable: true }
}
};
(function( d, t ) {
var g = d.createElement( t ), s = d.getElementsByTagName( t )[0];
g.src = 'https://api.reftagger.com/v2/RefTagger.js';
s.parentNode.insertBefore( g, s );
}( document, 'script' ));
</script>
<?php
} );
Keep in mind: The plugin's settings page exposes many Reftagger options; adjust the refTagger.settings object to match your preferences.
functions.php add_shortcode( 'current_date', function( $atts ) {
$atts = shortcode_atts( [
'format' => 'jS F Y',
'size' => '',
'color' => '',
], $atts, 'current_date' );
$date = date_i18n( $atts['format'] );
if ( $atts['size'] || $atts['color'] ) {
$style = '';
if ( $atts['size'] ) $style .= 'font-size:' . esc_attr( $atts['size'] ) . ';';
if ( $atts['color'] ) $style .= 'color:' . esc_attr( $atts['color'] ) . ';';
return '<span style="' . $style . '">' . esc_html( $date ) . '</span>';
}
return esc_html( $date );
} );
Keep in mind: The Gutenberg block is not replicated by this snippet.
functions.php add_shortcode( 'redirect', function( $atts ) {
$atts = shortcode_atts(
[ 'url' => '', 'sec' => 0, 'show_message' => 'true' ],
$atts,
'redirect'
);
$url = esc_url( $atts['url'] );
$sec = max( 0, (int) $atts['sec'] );
if ( ! $url ) {
return '';
}
$show = ! in_array( strtolower( $atts['show_message'] ), [ 'false', '0', 'no', 'off' ], true );
$msg = $show ? '<p>Please wait, redirecting…</p>' : '';
return sprintf(
'<meta http-equiv="refresh" content="%d;url=%s">%s',
$sec,
$url,
$msg
);
} );
Keep in mind: The Gutenberg Redirect block is not replicated; this covers only the classic shortcode behaviour.
functions.php add_filter( 'widget_text', 'do_shortcode' );
Keep in mind: Since WordPress 4.9 the built-in Text widget already supports shortcodes natively, so this filter may not be needed at all on modern sites.
functions.php // Add ID column to posts, pages, and other post types
add_filter( 'manage_posts_columns', 'show_id_column' );
add_filter( 'manage_pages_columns', 'show_id_column' );
function show_id_column( $columns ) {
$columns['post_id'] = 'ID';
return $columns;
}
add_action( 'manage_posts_custom_column', 'show_id_column_value', 10, 2 );
add_action( 'manage_pages_custom_column', 'show_id_column_value', 10, 2 );
function show_id_column_value( $column, $post_id ) {
if ( 'post_id' === $column ) {
echo esc_html( $post_id );
}
}
// Add ID column to taxonomy term lists (categories, tags, etc.)
add_filter( 'manage_edit-category_columns', 'show_term_id_column' );
add_filter( 'manage_edit-post_tag_columns', 'show_term_id_column' );
function show_term_id_column( $columns ) {
$columns['term_id'] = 'ID';
return $columns;
}
add_filter( 'manage_category_custom_column', 'show_term_id_column_value', 10, 3 );
add_filter( 'manage_post_tag_custom_column', 'show_term_id_column_value', 10, 3 );
function show_term_id_column_value( $content, $column, $term_id ) {
if ( 'term_id' === $column ) {
return esc_html( $term_id );
}
return $content;
}
Keep in mind: This covers posts, pages, categories, and tags. Extend similarly for media, comments, and WooCommerce using the same column filter pattern.
functions.php add_shortcode( 'showmodule', function( $atts ) {
$atts = shortcode_atts( [ 'id' => 0 ], $atts, 'showmodule' );
$id = absint( $atts['id'] );
if ( ! $id ) {
return '';
}
$post = get_post( $id );
if ( ! $post || 'et_pb_layout' !== $post->post_type ) {
return '';
}
return do_shortcode( $post->post_content );
} );
Keep in mind: Assumes the Divi Builder is active and will process its own shortcodes inside the retrieved content.
functions.php add_action( 'login_form', function () {
$number = rand( 100, 999 );
echo '<p>
<label>Security Check: enter the number <strong id="simple-captcha-num"></strong><br>
<input type="text" name="simple_captcha" autocomplete="off" /></label>
<input type="hidden" name="simple_captcha_answer" id="simple-captcha-answer" />
</p>
<script>
var n = ' . $number . ';
document.getElementById("simple-captcha-num").textContent = n;
document.getElementById("simple-captcha-answer").value = n;
</script>';
} );
add_filter( 'authenticate', function ( $user, $username, $password ) {
if ( empty( $username ) && empty( $password ) ) {
return $user;
}
$answer = isset( $_POST['simple_captcha_answer'] ) ? intval( $_POST['simple_captcha_answer'] ) : 0;
$entered = isset( $_POST['simple_captcha'] ) ? intval( $_POST['simple_captcha'] ) : -1;
if ( $entered !== $answer || $answer === 0 ) {
return new WP_Error( 'captcha_failed', __( 'Incorrect security number. Please try again.' ) );
}
return $user;
}, 30, 3 );
Keep in mind: This does not cover the WooCommerce login form; add a similar hook to woocommerce_login_form and woocommerce_process_login if needed.
functions.php add_action( 'wp_footer', 'my_simple_side_tab' );
function my_simple_side_tab() {
$tab_text = 'Get a Quote';
$tab_url = '/contact/';
$side = 'right'; // 'left' or 'right'
$top = '40%';
$bg_color = '#e74c3c';
$text_color = '#ffffff';
?>
<style>
.simple-side-tab {
position: fixed;
<?php echo esc_attr( $side ); ?>: 0;
top: <?php echo esc_attr( $top ); ?>;
background: <?php echo esc_attr( $bg_color ); ?>;
color: <?php echo esc_attr( $text_color ); ?>;
writing-mode: vertical-rl;
text-orientation: mixed;
transform: <?php echo $side === 'right' ? 'rotate(180deg)' : 'none'; ?>;
padding: 14px 8px;
text-decoration: none;
font-weight: bold;
z-index: 9999;
border-radius: <?php echo $side === 'right' ? '6px 0 0 6px' : '0 6px 6px 0'; ?>;
}
</style>
<a class="simple-side-tab" href="<?php echo esc_url( $tab_url ); ?>">
<?php echo esc_html( $tab_text ); ?>
</a>
<?php
}
Keep in mind: Adjust the variables at the top of the function to match your desired text, URL, side, position, and colors.
functions.php add_action( 'template_redirect', function () {
if ( current_user_can( 'manage_options' ) ) {
return;
}
status_header( 503 );
wp_die( '<h1>Under Maintenance</h1><p>The site is temporarily unavailable. Please check back soon.</p>', 'Maintenance', [ 'response' => 503 ] );
} );
Keep in mind: The snippet does not flush cache plugins automatically or show the admin-bar alert banner.
functions.php // Set the envelope sender (Return-Path) and default From address/name.
add_action( 'phpmailer_init', function ( PHPMailer\PHPMailer\PHPMailer $mailer ) {
$from_email = '[email protected]'; // change to your sending address
$from_name = 'My Site Name'; // change to your sender name
$mailer->Sender = $from_email; // envelope sender / Return-Path
$mailer->From = $from_email;
$mailer->FromName = $from_name;
} );
// Override the default WordPress from email and name.
add_filter( 'wp_mail_from', fn() => '[email protected]' );
add_filter( 'wp_mail_from_name', fn() => 'My Site Name' );
Keep in mind: The plugin also displays SPF record info and blacklist checks in the admin UI, which the snippet does not replicate.
functions.php add_filter( 'style_loader_src', function( $src ) {
if ( strpos( $src, 'fonts.googleapis.com' ) !== false ) {
if ( strpos( $src, 'display=' ) === false ) {
$src = add_query_arg( 'display', 'swap', $src );
} else {
$src = preg_replace( '/display=[^&]+/', 'display=swap', $src );
}
}
return $src;
}, 10, 1 );
Keep in mind: This only covers fonts enqueued via wp_enqueue_style; fonts hard-coded in themes or loaded via @import in CSS are not affected.
Preloader Show a GIF preloader overlay until the page fully loads functions.php // Enqueue inline preloader styles and script
add_action( 'wp_head', function () {
echo '<style>
#preloader-overlay {
position: fixed; inset: 0; z-index: 99999;
background: #fff;
display: flex; align-items: center; justify-content: center;
transition: opacity 0.4s ease;
}
</style>';
} );
add_action( 'wp_body_open', function () {
echo '<div id="preloader-overlay">
<img src="' . esc_url( get_template_directory_uri() . '/images/preloader.gif' ) . '" alt="Loading" width="64" height="64">
</div>';
} );
add_action( 'wp_footer', function () {
echo '<script>
window.addEventListener("load", function () {
var el = document.getElementById("preloader-overlay");
if (el) { el.style.opacity = "0"; setTimeout(function(){ el.remove(); }, 400); }
});
</script>';
} );
Keep in mind: The snippet uses a hardcoded GIF path and shows the preloader to all visitors on all pages; the plugin adds a UI to pick templates, target specific pages, and restrict by user role.
Top Bar Display a simple notification bar at the top of the site functions.php // Configuration
define( 'TOP_BAR_MESSAGE', 'Welcome to our site! Check out our latest news.' );
define( 'TOP_BAR_BTN_TEXT', 'Learn More' );
define( 'TOP_BAR_BTN_URL', 'https://example.com' );
define( 'TOP_BAR_BG_COLOR', '#333333' );
define( 'TOP_BAR_TEXT_COLOR', '#ffffff' );
add_action( 'wp_head', function () {
echo '<style>
#simple-top-bar { background:' . TOP_BAR_BG_COLOR . '; color:' . TOP_BAR_TEXT_COLOR . '; text-align:center; padding:10px 16px; font-size:14px; width:100%; box-sizing:border-box; }
#simple-top-bar a { color:' . TOP_BAR_TEXT_COLOR . '; background:rgba(255,255,255,.2); padding:3px 10px; border-radius:3px; text-decoration:none; margin-left:10px; }
</style>';
} );
add_action( 'wp_body_open', function () {
echo '<div id="simple-top-bar">' . esc_html( TOP_BAR_MESSAGE );
if ( TOP_BAR_BTN_TEXT && TOP_BAR_BTN_URL ) {
echo '<a href="' . esc_url( TOP_BAR_BTN_URL ) . '">' . esc_html( TOP_BAR_BTN_TEXT ) . '</a>';
}
echo '</div>';
} );
Keep in mind: Pro features like sticky scrolling, close button, delayed appearance, and bottom positioning are not included.
functions.php add_action( 'template_redirect', function () {
// Allow logged-in users (admins, editors, etc.) through.
if ( is_user_logged_in() ) {
return;
}
// Don't redirect the maintenance page itself (adjust slug as needed).
if ( is_page( 'maintenance' ) ) {
return;
}
wp_redirect( home_url( '/maintenance/' ) );
exit;
} );
Keep in mind: The snippet only handles the redirect logic; the actual maintenance page, its design, SEO meta, analytics, logo, social icons, and date scheduling are not included.
functions.php // Add post IDs to exclude in this array.
$unlisted_ids = [42, 99, 123];
add_action( 'pre_get_posts', function ( WP_Query $query ) use ( $unlisted_ids ) {
if ( is_admin() || empty( $unlisted_ids ) ) {
return;
}
$existing = $query->get( 'post__not_in' ) ?: [];
$query->set( 'post__not_in', array_unique( array_merge( $existing, $unlisted_ids ) ) );
} );
Keep in mind: The plugin stores the unlisted flag per post via a meta box UI; this snippet requires you to hardcode the IDs or replace the array with a get_posts/meta query to fetch posts marked with a custom field.
functions.php add_action( 'personal_options_update', 'update_username_on_profile_save' );
add_action( 'edit_user_profile_update', 'update_username_on_profile_save' );
function update_username_on_profile_save( $user_id ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
$new_username = sanitize_user( $_POST['new_username'] ?? '' );
if ( $new_username && ! username_exists( $new_username ) ) {
global $wpdb;
$wpdb->update( $wpdb->users, [ 'user_login' => $new_username ], [ 'ID' => $user_id ] );
wp_cache_delete( $user_id, 'users' );
}
}
add_action( 'show_user_profile', 'render_username_field' );
add_action( 'edit_user_profile', 'render_username_field' );
function render_username_field( $user ) {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
echo '<h3>Change Username</h3>
<table class="form-table"><tr>
<th><label for="new_username">New Username</label></th>
<td><input type="text" name="new_username" id="new_username" class="regular-text" /></td>
</tr></table>';
}
Keep in mind: This snippet adds the field to the existing user profile page; it omits the dedicated admin list view, user search, and the email notification to the user.
functions.php add_filter( 'woocommerce_variable_price_html', function( $price, $product ) {
$prices = $product->get_variation_prices( true );
if ( empty( $prices['price'] ) ) {
return $price;
}
$min_price = min( $prices['price'] );
$max_price = max( $prices['price'] );
if ( $min_price === $max_price ) {
return wc_price( $min_price );
}
// Change this line to: wc_price( $max_price ) for "Up to", or
// wc_price( $max_price ) . ' - ' . wc_price( $min_price ) for max-to-min.
return sprintf( __( 'From %s', 'woocommerce' ), wc_price( $min_price ) );
}, 10, 2 );
Keep in mind: This snippet shows the "From minimum price" format only; swap the return value to replicate the other formats the plugin offers.
Version Info Display PHP, MySQL, WP, and server versions in admin footer functions.php add_filter( 'admin_footer_text', function ( $text ) {
global $wpdb;
$wp = get_bloginfo( 'version' );
$php = phpversion();
$mysql = $wpdb->db_version();
$server = $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown';
return $text . sprintf(
' | WP %s | PHP %s | MySQL %s | %s',
esc_html( $wp ),
esc_html( $php ),
esc_html( $mysql ),
esc_html( $server )
);
} );
Keep in mind: The snippet covers the free footer display only; the admin bar nodes, dashboard widget, update alerts, and all PRO features are not included.
CSS @view-transition {
navigation: auto;
}
Keep in mind: This is the entire modern CSS spec for cross-document view transitions; no PHP or JS is needed.
functions.php // Add plus/minus buttons around WooCommerce quantity inputs
add_action( 'woocommerce_before_quantity_input_field', function () {
echo '<button type="button" class="qty-btn qty-minus" aria-label="' . esc_attr__( 'Decrease quantity', 'woocommerce' ) . '">-</button>';
} );
add_action( 'woocommerce_after_quantity_input_field', function () {
echo '<button type="button" class="qty-btn qty-plus" aria-label="' . esc_attr__( 'Increase quantity', 'woocommerce' ) . '">+</button>';
} );
// JS: handle button clicks
add_action( 'wp_footer', function () {
if ( ! is_woocommerce() && ! is_cart() ) return;
?>
<script>
document.addEventListener('click', function (e) {
var btn = e.target.closest('.qty-minus, .qty-plus');
if (!btn) return;
var input = btn.parentNode.querySelector('input.qty');
if (!input) return;
var step = parseFloat(input.step) || 1;
var min = parseFloat(input.min) || 0;
var max = parseFloat(input.max) || Infinity;
var val = parseFloat(input.value) || min;
val = btn.classList.contains('qty-plus') ? val + step : val - step;
input.value = Math.min(Math.max(val, min), max);
input.dispatchEvent(new Event('change', {bubbles: true}));
});
</script>
<?php
} );
Keep in mind: The plugin adds a settings UI for custom button colors, border radius, and hover styles; those must be replicated with CSS manually.
functions.php // Replace with your GA4 Measurement ID or GTM container ID.
define( 'WK_GA_ID', 'G-XXXXXXXXXX' );
define( 'WK_GTM_ID', 'GTM-XXXXXXX' );
// Skip tracking for logged-in users.
add_action( 'wp_head', function () {
if ( is_user_logged_in() ) {
return;
}
$ga_id = WK_GA_ID;
$gtm_id = WK_GTM_ID;
if ( $gtm_id ) {
echo "<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','{$gtm_id}');</script>\n";
} elseif ( $ga_id ) {
echo "<script async src='https://www.googletagmanager.com/gtag/js?id={$ga_id}'></script>
<script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config','{$ga_id}',{'anonymize_ip':true});</script>\n";
}
}, 1 );
Keep in mind: The plugin's "ignore this device" cookie opt-out and its settings UI are not replicated here.
functions.php // Set default products per page
add_filter( 'loop_shop_per_page', function( $cols ) {
$per_page = isset( $_COOKIE['wc_products_per_page'] ) ? (int) $_COOKIE['wc_products_per_page'] : 12;
return $per_page > 0 ? $per_page : $cols;
}, 20 );
// Render the dropdown and save choice in a cookie
add_action( 'woocommerce_before_shop_loop', function() {
$options = [ 12, 24, 48, -1 ];
$current = isset( $_COOKIE['wc_products_per_page'] ) ? (int) $_COOKIE['wc_products_per_page'] : 12;
$labels = array_map( fn( $n ) => $n === -1 ? __( 'All', 'woocommerce' ) : $n, $options );
echo '<form method="get" class="products-per-page-form" style="margin-bottom:1em;">';
echo '<label for="ppp">' . esc_html__( 'Products per page:', 'woocommerce' ) . ' </label>';
echo '<select name="ppp" id="ppp" onchange="this.form.submit()">';
foreach ( $options as $i => $val ) {
printf(
'<option value="%1$d"%2$s>%3$s</option>',
$val,
selected( $current, $val, false ),
esc_html( $labels[ $i ] )
);
}
echo '</select></form>';
}, 30 );
// Store the chosen value in a cookie
add_action( 'init', function() {
if ( isset( $_GET['ppp'] ) ) {
$val = (int) $_GET['ppp'];
setcookie( 'wc_products_per_page', $val, time() + MONTH_IN_SECONDS, '/' );
$_COOKIE['wc_products_per_page'] = $val;
}
} );
Keep in mind: The snippet hardcodes the option list and dropdown position; the plugin offers configurable options, columns per page, and bottom placement via its settings screen.
functions.php // Assign a sequential order number when a new order is created.
add_action( 'woocommerce_new_order', 'set_sequential_order_number', 10, 1 );
function set_sequential_order_number( $order_id ) {
$max = (int) get_option( 'sequential_order_number_max', 0 );
$next = max( $max, $order_id ) + 1;
update_option( 'sequential_order_number_max', $next );
update_post_meta( $order_id, '_order_number', $next );
}
// Display the sequential number instead of the post ID.
add_filter( 'woocommerce_order_number', 'display_sequential_order_number', 10, 2 );
function display_sequential_order_number( $order_number, $order ) {
$sequential = get_post_meta( $order->get_id(), '_order_number', true );
return $sequential ? $sequential : $order_number;
}
Keep in mind: The snippet does not include a find_order_by_order_number helper or handle edge cases like order restoration from trash.
functions.php // Add a custom meta box for the body class field
add_action( 'add_meta_boxes', function () {
add_meta_box( 'custom_body_class', 'Custom Body Class', function ( $post ) {
$value = get_post_meta( $post->ID, '_custom_body_class', true );
echo '<input type="text" name="custom_body_class" value="' . esc_attr( $value ) . '" style="width:100%">';
}, [ 'post', 'page' ], 'side' );
} );
// Save the meta value
add_action( 'save_post', function ( $post_id ) {
if ( isset( $_POST['custom_body_class'] ) ) {
update_post_meta( $post_id, '_custom_body_class', sanitize_html_class( $_POST['custom_body_class'] ) );
}
} );
// Inject the class into the body
add_filter( 'body_class', function ( $classes ) {
if ( is_singular() ) {
$custom = get_post_meta( get_the_ID(), '_custom_body_class', true );
if ( $custom ) {
$is_mobile = wp_is_mobile();
if ( str_starts_with( $custom, 'mobile-' ) ) {
if ( $is_mobile ) {
$classes[] = sanitize_html_class( substr( $custom, 7 ) );
}
} else {
$classes[] = sanitize_html_class( $custom );
}
}
}
return $classes;
} );
Keep in mind: This snippet handles one class per post; the plugin may support multiple space-separated classes or custom post types beyond post and page.
functions.php add_shortcode( 'wpdts-custom', function( $atts ) {
$atts = shortcode_atts( [ 'format' => 'Y-m-d H:i:s' ], $atts );
return date_i18n( $atts['format'] );
} );
add_shortcode( 'wpdts-date', function() {
return date_i18n( get_option( 'date_format' ) );
} );
add_shortcode( 'wpdts-time', function() {
return date_i18n( get_option( 'time_format' ) );
} );
add_shortcode( 'wpdts-year', function() {
return date_i18n( 'Y' );
} );
add_shortcode( 'wpdts-month', function() {
return date_i18n( 'n' );
} );
add_shortcode( 'wpdts-day', function() {
return date_i18n( 'j' );
} );
Keep in mind: The plugin offers many more alias shortcodes and offset attributes; add extra add_shortcode calls for any you need.
WP Last Login Show sortable last login date column on Users screen functions.php // Record last login time.
add_action( 'wp_login', function ( $user_login, $user ) {
update_user_meta( $user->ID, 'last_login', time() );
}, 10, 2 );
// Register the column.
add_filter( 'manage_users_columns', function ( $columns ) {
$columns['last_login'] = 'Last Login';
return $columns;
} );
// Render the column value.
add_filter( 'manage_users_custom_column', function ( $output, $column, $user_id ) {
if ( 'last_login' !== $column ) {
return $output;
}
$time = get_user_meta( $user_id, 'last_login', true );
if ( ! $time ) {
return '—';
}
$date = date_i18n( get_option( 'date_format' ), $time );
$full = date_i18n( 'Y-m-d H:i:s', $time );
return '<span title="' . esc_attr( $full ) . '">' . esc_html( $date ) . '</span>';
}, 10, 3 );
// Make the column sortable.
add_filter( 'manage_users_sortable_columns', function ( $columns ) {
$columns['last_login'] = 'last_login';
return $columns;
} );
// Handle the sort query.
add_action( 'pre_get_users', function ( $query ) {
if ( ! is_admin() || 'last_login' !== $query->get( 'orderby' ) ) {
return;
}
$query->set( 'meta_key', 'last_login' );
$query->set( 'orderby', 'meta_value_num' );
} );
Keep in mind: Does not replicate multisite network-admin support or the filter hooks for custom date format and role-based visibility.
functions.php // Add "Buy Now" button after the Add to Cart button on product pages
add_action( 'woocommerce_after_add_to_cart_button', 'simple_buy_now_button' );
function simple_buy_now_button() {
global $product;
echo '<a href="' . esc_url( $product->add_to_cart_url() ) . '&buy_now=1" class="button buy-now-button">' . esc_html__( 'Buy Now', 'woocommerce' ) . '</a>';
}
// Handle the Buy Now redirect: clear cart, add product, redirect to checkout
add_action( 'wp_loaded', 'simple_buy_now_redirect' );
function simple_buy_now_redirect() {
if ( empty( $_GET['buy_now'] ) || empty( $_GET['add-to-cart'] ) ) {
return;
}
$product_id = absint( $_GET['add-to-cart'] );
$quantity = isset( $_GET['quantity'] ) ? absint( $_GET['quantity'] ) : 1;
WC()->cart->empty_cart();
WC()->cart->add_to_cart( $product_id, $quantity );
wp_safe_redirect( wc_get_checkout_url() );
exit;
}
Keep in mind: This covers the core single-product flow only; category filtering, shop-page buttons, shortcode placement, variable products, and the premium Instant Checkout popup are not included.