Different Ways to Add Custom Code Snippets in WordPress

Custom Code Snippets in WordPress Featured Image

Used by more than 60 million websites, WordPress is a popular, powerful and flexible Content Management System (CMS). One of WordPress’ valuable features is its extensibility architecture that allows users to expand WordPress features via plugins. In many cases, site owners need custom codes to improve the functionality of their website. In this way, custom code snippets plugins in WordPress can be a handy tool.

Sometimes when surfing the internet, we come across articles that explain how to add custom code snippets to the template files like index.php, footer.php or edit function.php files. These methods aren’t safe or recommended.

There are only two safe methods to add custom code snippets in WordPress:

  • Using plugins
  • Using the child theme

Adding Custom Code Snippets in WordPress Using Plugins

There are some plugins that allow you to add custom PHP, HTML, CSS and JavaScript codes in WordPress. In this article, we try to cover some of them with examples. Some of the plugins are listed below.

Insert the PHP Code Snippets Plugin

Custom Code Snippets in WordPress - Insert PHP Code Snippet

Using this plugin, we can add our PHP code conveniently to our pages, posts and widgets.

Features

  • Convert PHP snippets to shortcodes.
  • Insert PHP code easily using a shortcode.
  • Support for PHP snippet shortcodes in widgets.
  • Dropdown menu in TinyMCE editor to easily select snippet shortcodes.

Example

In this example, we want to display the number of content words in a post/page after a post or page.

1. After installing this plugin, click on PHPCode Snippet from the left sidebar of the admin page.

Custom Code Snippets in WordPress - PHP Code Snippets

2. On the new screen, click on the Add New PHP Code Snippet button.

Custom Code Snippets in WordPress - PHP Code Snippets 2

3. Set

  • Tracking Name: words-count
  • PHP code (this code displays the words count for a page or content post)
<?php

  function word_count() {
       $content = get_post_field( 'post_content', get_the_ID());
       $word_count = str_word_count( strip_tags( $content ) );
       return $word_count;
    }

  echo 'Words:', '  ' , word_count();

?>
Custom Code Snippets in WordPress - PHP Code Snippets 3

4. Click on the Create/Update button.

5. The plugin generates a shortcode as [xyz-ips snippet=”words-count”].

Custom Code Snippets in WordPress - PHP Code Snippets 4

6. Go to Posts > Add New. At the end of the text, insert the above shortcode.

Custom Code Snippets in WordPress - PHP Code Snippets 5

7. After publishing the post, we can see the number of words in the post.

Insert the HTML Snippet Plugin

custom code snippets in WordPress - Insert HTML Snippet

Inserting the HTML Snippet allows us to create shortcodes corresponding to HTML snippets. We can create a shortcode corresponding to any random HTML code such as JavaScript codes, video embedding codes, CSS codes, among others and use the same in posts, pages or widgets.

Features

  • Convert HTML snippets to shortcodes.
  • Convert Javascript codes to shortcodes.
  • Convert CSS codes to shortcodes.
  • Support for snippet shortcodes in widgets.
  • Dropdown menu in TinyMCE editor to pick snippet shortcodes easily.
  • Insert Adsense or any add codes.
  • Insert flash, videos, etc. to your posts, pages, and widgets.

Example

In this example, we want to generate a Google Translate button after our post.

1. Install the plugin, and go to XYZ HTML > HTML Snippets.

Custom Code Snippets in WordPress - HTML Code Snippets 1

2. On the new screen, click on the Add new HTML Snippet button.

Custom Code Snippets in WordPress - HTML Code Snippets 2

3. Set

  • Tracking Name: translate
  • HTML Code (this code generates the Google Translate button)
<div id="google_translate_element"></div>

<script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>

<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

4. Click on the Create button.

Custom Code Snippets in WordPress - HTML Code Snippets 3

5. The plugin will generate the shortcode as [xyz-ihs snippet=”translate”].

Custom Code Snippets in WordPress - HTML Code Snippets 4

6. Go to Posts > Add New. Set the title and content the add [xyz-ihs snippet=”translate”] at the end of the post.

Custom Code Snippets in WordPress - HTML Code Snippets 5

7. Publish the post, and you will be able to see the Google Translate button after the post.

Custom Code Snippets in WordPress - HTML Code Snippets 6

Simple Custom CSS and JS Plugin

Custom code snippets in WordPress - Custom Css

Customizing your WordPress site’s appearance can easily be done by adding custom CSS and JS code without modifying the theme or plugin files.

Features

  • Text editor with syntax highlighting.
  • Print the code inline or include it into an external file.
  • Print the code in the header or the footer.
  • Add CSS or JS to the frontend or the admin side.
  • Add as many codes as you want.
  • Keep your changes when you change the theme.

Example

In this example, we want to change the background color of the admin bar with the CSS snippet.

1. Install the plugin and go to Custom CSS & JS > Add Custom CSS.

Custom Code Snippets - Custom CSS 1

2. On the new screen, in the options section, check the Internal, Header, In Admin radio button and set the following:

  • Title : admin-bar-background-color
  • Code (code change background color of admin bar in the admin page)
#wpadminbar {
    background-color: rebeccapurple;
}
Custom Code Snippets in WordPress - Custom CSS 2

3. Click on the Publish button. You’ll be able to see that the admin bar background menu changed.

Custom Code Snippets in WordPress - Custom CSS 3

Code Snippets Plugin

Custom Code Snippets in WordPress - Code Snippets Plugin Banner

This is a powerful, simple and handy plugin that lets us add our PHP, HTML, CSS and JavaScript snippets to our websites.

Features

  • Providing a GUI interface.
  • Snippets can be activated and deactivated.
  • Categorize snippets with tags.
  • Snippets can be exported for transfer to another site.
  • Full-featured code editor.

Example #1

In this example, we want to disable standard widgets like Archives, Recent Posts, Recent Comments with the simple PHP snippet. The default page is similar to the image below:

Custom Code Snippets in WordPress - Code Snippets Plugin 1

1. Install the plugin, and go to Snippets > Add New.

Custom Code Snippets in WordPress - Code Snippets Plugin 2

2. On the new screen, set:

  • Title: Remove standard widget
  • Code (Remove Archives, Recent Posts, Recent Comments from the right sidebar of the homepage).
function unregister_default_wp_widgets() { 

    unregister_widget('WP_Widget_Archives'); 
    unregister_widget('WP_Widget_Recent_Posts'); 
    unregister_widget('WP_Widget_Recent_Comments'); 
}

add_action( 'widgets_init', 'unregister_default_wp_widgets', 1 ); 

3. Save and activate the snippet.

Custom Code Snippets in WordPress - Code Snippets Plugin 3

4. After reloading the homepage, you’ll be able to see that the Archives, Recent Posts, Recent Comments have been removed.

Custom Code Snippets in WordPress - Code Snippets Plugin 4

Example #2

In this example, we want to change the font size of the post with the JavaScript code.

1. Go to Snippets > Add New.

2. Set

  • Title: change the font size
  • Code ( Increase the font size when clicking on the post text and decrease font size when holding down the SHIFT key and clicking.)
add_action( 'wp_head', function () { ?>

<script        src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>

    <script>	
    $(document).ready(function(){
    $(".jupiterx-post-content").click(function(){
        if (event.shiftKey) {
            $(this).css({"font-size": "-=10%"});  
        } else {
            $(this).css({"font-size": "+=10%"});
        }
    });

  });

  </script>

<?php } );

3. Check the Only run on site front-end radio button and save it.

Custom Code Snippets in WordPress - Code Snippets Plugin 5

At the end, when clicking on the post text, the font size will have been changed.

Custom Code Snippets in WordPress - Code Snippets Plugin 6

Adding Custom Code Snippets in WordPress Using Child Theme

In WordPress, a child theme is a sub-theme that inherits all the functionality, style and features from the parent theme. The child theme is a safe way to change or modify the parent theme without modifying parent theme files.

Example

Let’s add our default content to the WordPress editor.

Our default content: “This is some custom content. I’m adding it to the post editor because I hate re-typing it.”

1. Active the child theme on your site (for more information, read this article.)

2. Go to Appearance > Editor.

Custom Code Snippets in WordPress - Child Theme 1

3. Open the functions.php file.

Custom Code Snippets in WordPress - Child Theme 2

4. Add the below code at the end of functions.php, then update it.

add_filter( 'default_content', 'my_editor_content' ); 

  function my_editor_content( $content ) { 
    $content = "This is some custom content I'm adding to the post editor  because I hate re-typing it."; 
 
    return $content;
}
Custom Code Snippets in WordPress - Child Theme 3

5. After modifying functions.php, go to Posts > Add New or Pages > Add New. You’ll be able to see that our default text has been added to the editor.

Custom Code Snippets in WordPress - Child Theme 4

Conclusion

In this article, we first introduced several plugins for adding custom code snippets in WordPress. We also included some examples on how to use HTML, CSS, JavaScript and PHP snippets using the plugins.

Finally, we showed how to add custom code snippets in WordPress with the child theme. Feel free to share your experience with us in the comments.

Recommended Posts