How to add code to head (via functions.php)

Estimated Reading Time: 2 min

Rate this post

To add code to the <head> section of your WordPress site via the functions.php file, you can use the wp_head action hook. Here’s a simple way to do this:

  1. Access your WordPress Dashboard: Log in to your WordPress admin panel.
  2. Navigate to Theme Editor: Go to Appearance > Theme Editor.
  3. Select the functions.php file: On the right sidebar, find and click on the functions.php file of your active theme.
  4. Add your code: Insert the following code snippet at the end of the functions.php file:
   function add_code_to_head() {
       ?>
       <!-- Your custom code goes here -->
       <script>
           // Example: Custom JavaScript code
           console.log('Hello, World!');
       </script>
       <link rel="stylesheet" href="https://example.com/style.css">
       <?php
   }
   add_action('wp_head', 'add_code_to_head');

Replace the comment and example code with your actual code, such as JavaScript, CSS links, or meta tags.

  1. Save Changes: After adding your code, click the “Update File” button to save your changes.
  2. Test Your Site: Visit your website to ensure that the code has been successfully added to the <head> section.

Always remember to back up your functions.php file before making changes, as errors can break your site. If you’re unsure, consider using a child theme or a site-specific plugin for custom code.

Photo of author

Flora

How to add code to head (via functions.php)

Published

I am Flora, the publisher and founder of *Be-Smart*, a platform dedicated to sharing insights and inspiration for living a fulfilling life. With a strong background in the web, my goal is to empower people to genuinely recognize and celebrate admirable actions big or small in themselves and others.