Posted on

Adding custom functions to a site

The Relevanssi knowledge base is full of code snippets and custom functions that you can use to enhance your site and to change how Relevanssi works. But where to place those snippets and functions?

There are many different methods of adding custom functions to your site, and I will go through them in this article.

Functions.php

The traditional method is to use the theme functions.php file. As the name suggests, this file exists for this purpose. WordPress will run everything you add here on every page load, both in the admin backend and front end.

With this approach, you need to be conscious of theme updates. If you have a theme that gets updates, it’s not good to modify the functions.php file. Updates to the theme will overwrite your modifications, making you lose all functionality added to the file.

In those cases, you need to use a child theme: the child theme inherits everything from the parent theme, and you can safely make changes to the theme files in the child theme. Updates to the parent theme won’t overwrite the changes in the child theme.

Creating child themes isn’t tricky, and some plugins help with the task.

Custom plugin

Another approach is to create a custom plugin to store all the modifications. Creating a plugin requires slightly more setup work, but adding new functions is just as easy as with the functions.php method once you have the custom plugin.

Using a plugin also has the added benefit of being independent of your theme. If you switch your theme, you don’t lose all the custom modifications you’ve done. Relevanssi custom functions are things you need, no matter which theme you use, so putting them in a plugin outside your theme makes sense.

You can find instructions for writing plugins on WordPress.org. The minimum plugin is straightforward: you can create a file called custom-functions.php in the /wp-content/plugins/ directory and put this in the file:

<?php
/**
 * Plugin Name: My custom functions
 */
  

Once you do that, “My custom functions” should show up in the WordPress Plugins list for you to activate, and then you can add custom functions to this file.

PHP snippets

Finally, the third approach uses a PHP snippet plugin that lets you add and edit PHP code snippets from the WP admin. My recommendation would be Code Snippets, a well-done plugin that does the job well. The plugin is easy to use, and it’s easy to manage the snippets and control how WordPress runs them.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *