Advanced Custom Fields is a widely used plugin that allows you to implement custom fields without having to develop a ton of code.
With more than 1 million installations, Advanced Custom Fields is a proven, well-developed, and well-supported plugin.
Install and activate the plugin and you will have a new menu option in your Administrative menu called “Custom Fields.” Our goal with this example is to add a field that’s available only to administrators that will embed either a JavaScript source file or JavaScript code within the head or before the closing body tag.
1. Navigate to Custom Fields > Custom Fields and click Add New.
2. Name your Field Group. We named ours JavaScript Settings.
3. We enabled a rule to display the option only if the logged in user type was Administrator, ensuring that the fields could only be applied by an administrator of the site.
4. We’d like to display the fields in a section beneath the content area on the text editor, so we’re going to select Standard on the style of the Field Group.
5. Now we need to add our Header Script and Footer Script custom fields and output them correctly. There are two key settings; the field name that will be referenced later in the template code and the formatting. You must set the formatting to the “Convert HTML into tags” option so that the contents that are pasted are properly executed in the template.
At this point, the fields will properly display within the Administration panel when an administrator is logged in. Any data entered will be saved and associated with the page or post once it’s saved or published. However, they will not display within the template until you edit your template files.
6. Within header.php in the active template, we will add:
<?php the_field(‘header_script'); ?>
before the </head> tag.
Within footer.php in the active template, we will add:
<?php the_field(‘footer_script'); ?>
before the </body> tag.
7. Save the template files, update the page or post that you’ve specified JavaScript in, and click publish. The page or post will now be published with the JavaScript properly inserted into the template.
The Advanced Custom Fields option offers quite a bit of functionality. You may want to define your rules specific to certain users, published pages, or page templates rather than Administrators and all posts and pages. We’d highly recommend narrowing down access to adding scripts to only the pages, posts and users that they are required for.