Skip to main content
All CollectionsSupplementary GuidesWordPressCodes
Code Snippets in WordPress: Usage and Best Practices
Code Snippets in WordPress: Usage and Best Practices
Rapyd Team avatar
Written by Rapyd Team
Updated over a year ago

Code snippets are excellent tools for customization. When used with understanding, and caution, they offer lots of potential to enhance your WordPress site.

Understanding Code Snippets

In WordPress, code snippets refer to small blocks of code that can be added to your WordPress site to modify or extend its functionality. They are typically used to add custom features, modify existing features, or fix specific issues.

Code snippets can be written in various programming languages, including PHP, JavaScript, HTML, and CSS, depending on the nature of the customization you want to achieve. These snippets are usually inserted into your site's theme files, such as the functions.php file for PHP code, or the header.php or footer.php files for HTML or JavaScript code.

Ways to Add Code Snippets to a WordPress Site

1. Theme Files

You can edit your theme's files directly using the WordPress theme editor or a code editor. This method requires some knowledge of coding and should be approached with caution, as incorrect modifications can break your site.

Read: Understanding WordPress Themes

2. Child Theme

If you're making changes to your theme's files, it's recommended to create a child theme. This allows you to make modifications without affecting the original theme files, making it easier to update your theme in the future.

Read: Leveraging WordPress Child Themes: Purpose, Functionality, and Benefits

3. Custom Plugin

Another approach is to create a custom plugin specifically for your code snippets. This method keeps your customizations separate from the theme files and ensures they won't be lost during theme updates. You can create a plugin by creating a new PHP file with the necessary code and placing it in the wp-content/plugins directory of your WordPress installation.

4. Code Snippet Plugins

There are several WordPress plugins available that allow you to add code snippets to your site without modifying theme files or creating custom plugins. These plugins provide a user-friendly interface for managing and adding code snippets.

For implementing snippets on your WordPress site, choose either a child theme or a plugin like Code Snippets. The following instructions are specifically for a child theme.

Step-by-Step Process to Use Child Theme for Code Snippets in WordPress

Enabling a specific functionality isn't available by default on the WordPress platform. However, you can incorporate it using the following method:

Please note that the code will only function correctly if the website is configured as Public.

Navigate to Appearance > Theme File Editor.

Choose the active theme (BuddyBoss Child/whatever theme is active) from the Select theme to edit dropdown, then click Select.

Locate 'Theme Functions (functions.php)' in the 'Theme Files' section.

Add the code right before the closing PHP tag "?>".

Follow the steps mentioned above to smoothly integrate the desired functionality into your website. Once you have completed these above-mentioned steps, you can proceed with the remaining instructions to implement any of the Code Snippets discussed below.

You can accomplish all of these by using WordPress plugins like Code Snippets as well.

Step-by-Step Process of Installing and Using Code Snippets Plugin in WordPress

First, Install and Activate the Code Snippets plugin from the WordPress plugin store.

Once activated, navigate to the WordPress admin area. From the left-hand menu, locate and click on Snippets. This will take you to the Code Snippets management page.

To add a new code snippet, click on the Add New button at the top of the page.

Provide a title for your snippet to help you identify it later. Then, in the Code section, enter your desired code snippet (You can choose snippets that are mentioned below).

Optionally, you can provide a description and tags for better organization and searchability.

After entering the code snippet, click on the Save Changes and Activate button to save and activate the snippet.

The snippet will be executed on your WordPress site based on its activation status.

To make the necessary changes, you will require the assistance of WordPress Snippets, which need to be placed in specific locations. Below, you will find a compilation of commonly used Code Snippets for your reference.

Common Code Snippets in WordPress

1. Create Clickable Logo for the Login Page

// The "login_headerurl" filter is used to filter the URL of the logo on the WordPress login page.
// By default, this logo links to the WordPress site.
add_filter('login_headerurl','crunchify_login_link');
function crunchify_login_link() {

// Change Logo link if you want user to redirect to other link.

return "https://page.url/";
}

Finally, Click on the Update File button to save the changes.

2. Including Separate Homepages for Logged In and Logged Out Users

if( is_user_logged_in() ) {
$page = get_page_by_path( 'page slug here');
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
}
else {
$page = get_page_by_path( 'page slug here' );
update_option( 'page_on_front', $page->ID );
update_option( 'show_on_front', 'page' );
}

Simply update the page slug here and the rest will automatically update. Make sure the slug corresponds to the desired page you wish to display for logged-in users.

Now, to configure the page for logged-out users, access the WP Dashboard, then proceed to Settings > Reading > Homepage.

Finally, Save the change.

3. Directing Users to their Profile Page upon Login

function redirect_to_page( $redirect_to_calculated, $redirect_url_specified, $user ) {
if ( ! $user || is_wp_error( $user ) ) {
return $redirect_to_calculated;
}
// If the redirect is not specified, assume it to be dashboard.
if ( empty( $redirect_to_calculated ) ) {
$redirect_to_calculated = admin_url();
}
// if the user is not site admin, redirect to his/her profile.
if ( function_exists( 'bp_core_get_user_domain' ) && ! is_super_admin( $user->ID ) ) {
return "https://your-domain.com/your-link/";
}
// if site admin or not logged in, do not do anything much.
return $redirect_to_calculated;
}
add_filter( 'login_redirect', 'redirect_to_page', 100, 3 );

Finally, Click on the Update File button to save the changes.

4. Restricting Access to WP Admin Area for Users

function bb_restrict_admin_only() {
if ( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
wp_safe_redirect( site_url() );
exit;
}
}
add_action( 'admin_init', 'bb_restrict_admin_only', 1 );

Finally, Click on the Update File button to save the changes.

5. Enabling Automatic User Registration

function disable_validation( $user_id ) {
global $wpdb;
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->users SET user_status = 0 WHERE ID = %d", $user_id ) );
}
add_action( 'bp_core_signup_user', 'disable_validation' );
function fix_signup_form_validation_text() {
return false;
}
add_filter( 'bp_registration_needs_activation', 'fix_signup_form_validation_text');

Best Practices of Code Snippets in WordPress

Here are some best practices to follow when using code snippets in WordPress:

1. Backup Your Site: Always backup your site before adding or modifying code snippets. This way, if something goes wrong, you can easily restore your site to its previous state.

2. Understand the Code: Never add a code snippet to your site unless you understand what it does. Adding unknown code can lead to unexpected results or security vulnerabilities.

3. Test in a Staging Environment: If possible, test new code snippets in a staging environment before adding them to your live site. This allows you to see the impact of the code without risking your live site.

4. Use Comments: Comment your code snippets clearly so you and others can understand their purpose in the future. This is particularly important if you are working with a team or plan to pass the project to someone else.

5. Avoid Theme's Functions.php: It's generally not a good idea to add code snippets directly to your theme's functions.php file unless you're using a child theme. If you update or switch your theme, your modifications will be lost.

6. Use a Site-Specific Plugin or Child Theme: Instead of modifying your theme's functions.php file, consider creating a site-specific plugin or a child theme. This way, your modifications won't be lost when you update or change your theme.

7. Code Quality: Follow WordPress coding standards and best practices. This makes your code easier to read, maintain, and less prone to errors.

8. Keep it Minimal: Only use the necessary code snippets that add value to your site. Every new code snippet can add potential security risks, conflicts with other plugins or themes, and may slow down your site.

9. Stay Updated: Keep up with WordPress updates and changes. Code that worked in a previous version of WordPress might not work in a later version.

10. Use a Code Snippet Plugin: If you're uncomfortable editing PHP files directly, you can use a code snippet plugin that provides a more user-friendly interface for adding and managing your code snippets.

Read: Creating and Managing Template Files on WordPress

Conclusion

Using code snippets can significantly extend your WordPress site's functionality. However, caution is required. Always backup your site, understand the implemented code, and test it. Aim for security, efficiency, and simplicity. If unsure, consider professional assistance or use an equivalent plugin.

Did this answer your question?