WordPress is one of the most flexible platforms out there, giving you endless ways to customize your website. While plugins and themes make it easy to add features, sometimes you need a little extra control to make your site truly your own. That’s where the Code Snippets Plugin comes in! This handy tool lets you add custom PHP code to your site safely, without having to mess with core WordPress files or worry about breaking things. In this guide, I’ll show you how to use the Code Snippets Plugin, and I’ll share some must-have snippets you can easily copy and use to make your website more functional, secure, and unique. Let’s dive in!
How to Use Code Snippest:
- Install and activate the Code Snippets Plugin on your WordPress site.
- Go to Snippets > Add New in your WordPress admin panel.
- Give your snippet a title whatever you copying the related code. e.g “Disable Author Archives.”
- Copy and paste the code into the code editor.
- Save and activate the snippet.
Or
You can directly open function.php
and paste the copied code in the your theme file. But make sure you’re using the child theme, because if you directly add it to your main theme then it would be rewrite in future theme updates.
Disable Author Archives
Here’s a code snippet you can use to disable author archives in WordPress:
// Disable Author Archives
add_action('template_redirect', function () {
if (is_author()) {
wp_redirect(home_url()); // Redirect to the homepage
exit;
}
});
How It Works:
- The code uses the
template_redirect
hook to check if the current page is an author archive (is_author()
). - If it is, the user is redirected to the homepage using
wp_redirect(home_url())
Results:
This will ensure that all author archive pages are disabled and visitors are redirected to your homepage instead.
Disable Comments on the Posts
Here’s a simple code snippet to disable comments on all posts in WordPress:
// Disable Comments on All Posts
add_action('init', function () {
// Close comments on the front end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);
});
// Redirect Comments Pages
add_action('template_redirect', function () {
if (is_comment_feed()) {
wp_redirect(home_url());
exit;
}
});
How It Works:
- Disable Comments:
- The
comments_open
andpings_open
filters are set tofalse
, ensuring that no new comments can be added. - The
comments_array
filter hides any existing comments from being displayed.
- The
- Redirect Comment Pages:
- The
template_redirect
hook ensures that comment-related pages (like RSS feeds) are redirected to the homepage.
- The
Results:
This will effectively disable comments across all posts on your WordPress site and prevent comment feeds from being accessed.