One place for hosting & domains

      How to Add Custom Fields to Your WordPress Posts


      As you become comfortable with WordPress, you may want to start pushing its boundaries. This means experimenting with some of the platform’s more advanced options, which includes learning how to create custom fields.

      Adding a custom field to your WordPress post enables you to assign extra data to it. In turn, this helps you add specific information or features only to particular posts. As an example, you could use a custom field to tell WordPress which of your posts are sponsored, then add some code to your theme file that will display a disclosure statement only on those posts.

      An Introduction to Custom Fields

      The WordPress Block Editor is pretty flexible by default and enables you to customize your content to the Nth degree. You can add just about anything you like to your posts. However, the more content you have, the more you may start wishing for better ways to organize and manage it.

      Custom fields are a somewhat more advanced WordPress feature that lets you add extra information to specific posts. That information is called ‘metadata’. Custom fields and metadata are of particular use to developers, who can use them to extend posts with all sorts of additional coding. However, they can still be beneficial for the more general WordPress users.

      For example, let’s say you wanted to indicate which of the posts on your blog are sponsored to ensure you’re being transparent with your audience. You could add a short disclosure statement to each relevant post individually. Alternatively, you could save time by using a custom field that displays a relevant message. Then, you could add code to your theme file to make your disclosure statement appear on the correct posts.

      If this sounds complex, don’t worry. Using custom fields is more straightforward than it looks. In fact, we’ll show you exactly how to implement this example below. If you’re interested in other potential applications for custom fields and metadata, you may also want to check out the WordPress Codex entry on the topic.

      How to Add Custom Fields to Your WordPress Posts (In 2 Steps)

      The concept of custom fields might seem a bit abstract, so let’s walk through an example to see exactly how this feature works in action. This general custom field process can be used for a wide variety of applications. You could add status updates to your posts, include a disclosure notice on sponsored content, and much more.

      However, you’ll first want to take a moment and back up your website. If you’re following these instructions, you’ll be implementing changes to your theme’s primary file, and you don’t want to risk making any permanent mistakes. For extra security, creating a child theme and using it instead of your base theme is also advisable.

      Step 1: Enable Custom Fields and Assign New Metadata to Your Post

      The first thing you’ll need to do is open up a post to which you would like to add a custom field. It can be an old post or a new one.

      Click on the three dots in the top right corner and select Preferences from the dropdown list:

      Accessing Preferences from the WordPress Block Editor

      Then, select Panels from the popup menu and enable Custom fields. You’ll now be prompted to Enable & Reload:

      Enabling custom fields with the WordPress Block Editor

      Now, if you scroll down below the post, you’ll find a new section:

      Adding custom fields to a post in WordPress

      Under Name and Value, you’ll add some metadata describing the information you want to add to this post. Depending on the themes and plugins you have installed, you may already have some options listed under Name. Regardless, you’ll want to create new metadata in this instance.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      Choose a name for your metadata. It can be anything, although it’s best to keep it short and descriptive. Continuing our example from above about displaying a disclosure statement on specific posts, we’ll call it Sponsored Post. Then we’ll add a simple “Yes” to the Value box, indicating that this particular post is sponsored:

      Click on Add Custom Field, and this metadata will now be assigned to your post. Don’t forget to save or update the post itself too.

      Step 2: Add Conditional Code to Your Theme File

      The previous step told WordPress a critical piece of information about your post: whether or not it is sponsored content. Now, you need to add directions so that your site knows what to do about that. As we mentioned earlier, this does involve a bit of coding. However, don’t let that scare you off. Even if you aren’t a developer, you should find the process relatively straightforward.

      Within WordPress, you’ll want to navigate to Tools > Theme File Editor. Here, you can look through and make changes to the files that make up your site. You’ll want to check out the sidebar on the right-hand side and find the Single Post file (also known as single.php):

      This is where you’ll add the code that will tell WordPress what to do in response to your custom fields. The exact code you’ll use will vary somewhat, depending on what you want to do. In our example, you’d want to add this snippet:

      <?php
      $meta = get_post_meta( get_the_ID(), 'Sponsored Post' );
      if( $meta[0] == 'Yes' ) {
      ?>
      <p>This post is sponsored content, and we received a free copy of the product in order to conduct our review.</p>
      <?php } ?>

      Then, click on the Update File button. This code tells WordPress to check and see if a post has the Sponsored Post custom field and if the value is set to “Yes”. If so, it will display the message. If there is no custom field or the Sponsored Post value is set to “No”, nothing extra will be added to the post.

      Also, where you place the code will determine when it appears in the post. For example, to get it to appear at the top of the page, you would add it before this line in the single.php file:

      while ( have_posts() ) : the_post();

      Hopefully, you are beginning to see how custom fields can be useful. There are a lot of possibilities when using this feature, so don’t be afraid to play around a little and see what you can accomplish with it.

      Using Plugins to Manage Your Custom Fields

      You now know how to add custom fields and metadata to your WordPress posts. However, what if you want to get more flexibility from this feature or just want to simplify the process?

      This is WordPress we’re talking about, so of course, there are plugins that can help you out. There may not be a lot of plugins related to custom fields, but you can find a few quality options. For a great example, check out Advanced Custom Fields:

      Advanced Custom Fields plugin.

      This very popular, free plugin streamlines the process of adding custom fields to WordPress. It also gives you more choices for where metadata can be added, such as users, media, and comments. Finally, it adds tools to provide more options for displaying custom field values within your theme files. There’s even a premium version with even more functionality.

      If that plugin seems like overkill — and it can be for non-developers — Custom Field Suite is a solid alternative:

      Custom Field Suite WordPress plugin

      This tool is essentially a lightweight version of Advanced Custom Fields. It adds a handful of useful new custom field types to your site. Plus, it simplifies adding and managing custom fields without overwhelming you with too many new options.

      This can be a smart plugin to start with if you’re looking to get more out of your custom fields. What’s more, you can always switch to a more robust solution once you feel more confident with the process.

      Add Custom Fields to WordPress Content

      Custom fields and metadata are concepts that might seem a smidge confusing at first. However, with time and patience, you’ll find that they enable you to get even more out of the WordPress platform.

      Want a Free Theme?

      When you host with DreamHost you get access to our WP Website Builder tool and more than 200+ industry-specific starter sites for free!

      custom website design



      Source link

      Add a Promo Code


      A promo code adds a positive credit to an account, allowing you to pay for services using that credit. You’re able to add a promo code when signing up for an account. If you already signed up but haven’t entered a promo code, you may be able to do so from the Cloud Manager. To add a promo code to an existing account, certain conditions must be met:

      • The account must be less than 90 days old.
      • There must not be a negative balance on the account.
      • No other promo codes can already be applied to the account.
      • The user that’s logged in must have unrestricted permissions.

      If those conditions are met, you can add a promo code by following these instructions:

      1. Navigate to the Billing Info page in the
        Cloud Manager (see
        Accessing Billing Information).

      2. Under the Account Balance section, click the Add a promo code link.

        Account balance section of the Billing Info page

      3. In the Add promo code dialog box that is displayed, enter the promo code and click the Apply Promo Code button. You should now see the promotional credit amount reflected in your account balance.

      This page was originally published on



      Source link

      An Essential Guide on How to Add JavaScript to HTML


      JavaScript is a scripting language that is widely used to add dynamic functionality to a web page, alongside HTML and CSS. User triggered events, animations, and content updates are among some of the features on a web page that are powered by JavaScript. In order to use JavaScript on an HTML web page, you must use the <script> tag to either write your JavaScript code directly in your HTML markup or to link to an external JavaScript file. This guide shows you how to use the <script> tag to link JavaScript to an HTML page. You also learn about <script> tag attributes that help you optimize your web page’s loading time.

      The <script> tag is used to add JavaScript to an HTML web page. The following sections further explain how the <script> tag behaves when added to HTML markup and the different ways you can use it to add JavaScript to a web page.

      What is a <script> Tag?

      The <script> tag can be used to embed JavaScript into a web page in the following two ways:

      • Writing JavaScript code directly within an opening and closing <script> tags.
      • Referencing the path to a JavaScript file using the <script> tag’s src attribute.

      In both cases, when the HTML page loads, the web browser executes any JavaScript that it finds, in sequential order. There are two useful principles to keep in mind when using the <script> tag:

      • The JavaScript contained within or referenced by <script> tags is executed immediately when its portion of the page loads. So, a <script> tag placed within a page’s <head> tag executes before the HTML body. A <script> tag placed just before the end of the closing </body> tag, on the other hand, executes after everything else on the page has loaded and rendered.

      • The JavaScript used in your HTML markup defines functions and variables in the global scope. This means that if your web page has two <script> tags — say, one at the beginning and one at the end — they can reference the same functions and variables.

        Keep in mind that the code still follows the ordering described in the point above. For that reason, a script at the beginning of a web page cannot reference a variable assigned in a script at the end of the web page.

      How to Add JavaScript to HTML

      You can add JavaScript to your HTML markup by embedding JavaScript code between opening and closing <script> tags. For example, to add an alert box to an HTML page with a message that reads The script is working, add the following code to your HTML markup:

      <script>
          alert("The script is working!");
      </script>
      

      This example adds the JavaScript code directly to the HTML markup.

      The next example demonstrates the <script> tag contained within the body of an HTML page. As the browser sequentially executes the HTML, when it encounters the <script> tag, it executes the JavaScript within the tag. The JavaScript adds an event listener to the button with id="exampleButton". If a user clicks on the button, an alert box presents the message passed as an argument to the alert() method.

      File: example.html
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      
      <!doctype html>
      <html lang="en">
        <head>
          <title>Example Web Page with JavaScript</title>
        </head>
        <body>
          <button id="exampleButton">Click Me!</button>
          <script>
              exampleButtonElement = document.getElementById("exampleButton");
              exampleButtonElement.addEventListener("onclick", () => {
                  alert("The button has been clicked!");
              }
          </script>
        </body>
      </html>

      In the example, the <script> tag is placed after the <button> tag. This is necessary because the JavaScript references the button element. If the JavaScript had been inserted any earlier, the button element would not yet have been created by the time the JavaScript executes.

      Adding External JavaScript Files

      As your JavaScript code gets more complicated, you are likely to prefer keeping it in an external JS file, rather than including the script directly in your HTML markup.

      To include an external JavaScript file in HTML, you still use the <script> tag. However, instead of adding JavaScript directly between the <script> tags, you use the tag’s src attribute to point to an external JS file. The steps below give you a simple example that references an external JavaScript file HTML markup.

      The steps below assume that you are developing a simple website on your local computer. Your site files are stored in a directory named example-site.

      1. In your example-site directory, add a new subdirectory named js_files. This directory stores any JavaScript files that are referenced by HTML files.

        mkdir js_files
        
      2. Using your preferred text editor, add a new file named example.js to the js_files directory with the JavaScript displayed below.

        File: ~/username/js_files/example.js
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        
        // Create a button element.
        const buttonElement = document.createElement("button");
        const buttonElementText = document.createTextNode("Click Me!");
        buttonElement.appendChild(buttonElementText);
        
        // Add a 'click' event to that button element.
        buttonElement.addEventListener("click", () => {
            alert("The button has been clicked!");
        });
        
        // Insert the button element into the body of the web page.
        document.body.appendChild(buttonElement);
            
        
      3. Create an HTML file with the example markup. The markup uses the <script> tag to reference the JavaScript file created in the previous step.

        File: ~/username/example.html
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        
        <!doctype html>
        <html lang="en">
          <head>
            <title>Example Web Page with JavaScript</title>
          </head>
          <body>
            <script src="js_files/example.js"></script>
          </body>
        </html>
            

        The src attribute uses the relative path to the example.js file that contains the JavaScript code you want to execute.

      4. Visit the HTML page in a browser by entering the following address: file:///home/username/example-site/example.html. Click on the button and observe that it produces an alert dialog.

        You can also see the result by
        viewing our included example.html file
        .

      Defining <script> Tag Attributes

      Like all other HTML tags, the <script> tag supports a series of attributes that you can use to further control the behavior of the JavaScript that is executed on a web page. The list below contains some of the most useful attributes.

      • The async attribute tells the browser to download the referenced JavaScript file as the web page is parsed. Once the file has downloaded, its contents are immediately executed.

      • The defer attribute tells the browser to download a JavaScript file as the web page is parsed. The file is only executed once the entire web page has loaded.

      • The type attribute is used to identify the kind of script that is referenced by the src attribute. However, since JavaScript has become the unambiguous standard, this attribute is rarely necessary anymore.

      • The charset attribute lets you define a different character set for an external JavaScript file. This attribute, though common to see, is
        considered deprecated
        since documents now must use UTF-8.

      The sections below dive deeper into the two most useful <script> tag attributes, async and defer. These sections discuss how these attributes can be used to improve a web page’s performance.

      Async

      Normally, when a browser encounters the <script> tag with a linked JavaScript file, it stops loading the HTML in order to start downloading the referenced JavaScript file. Using the async attribute, it is possible to improve your web page’s performance by having the browser download the JavaScript file in the background while the page continues to load.

      The example file’s script tag makes use of the async attribute.

      File: index.html
      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      <!doctype html>
      <html lang="en">
        <head>
          <title>Example Web Page with JavaScript</title>
        </head>
        <body>
          <script src="js_files/main.js" async></script>
        </body>
      </html>

      It’s not always advisable to use the async attribute. For instance, if your script depends on certain elements not yet being rendered, or if the elements themselves depend on the script creating certain elements, async would likely be a problematic choice. When such cases are not a concern, async can help with your page’s load speed and user experience.

      Defer

      Like async, using defer tells the browser to download a linked JavaScript file in the background while the page continues to load. Unlike async, however, defer prevents the loaded script from being executed until the page has been fully rendered. This makes defer especially useful when your JavaScript code relies on one or more elements being rendered and available. Because defer ensures that the script only runs once the page has been loaded completely, you can be assured that the script does not run until all required elements are present on the page.

      File: index.html
      1
      2
      3
      4
      5
      6
      7
      8
      9
      
      <!doctype html>
      <html lang="en">
        <head>
          <title>Example Web Page with JavaScript</title>
        </head>
        <body>
          <script src="js_files/main.js" defer></script>
        </body>
      </html>

      Conclusion

      This guide covered the foundational information you need to start using JavaScript on your HTML pages. Whether you plan to embed a script or link a JavaScript file in your HTML, this guide outlined the steps needed to do so.

      As a next step, you may be interested in looking at some of our other JavaScript tutorials. For instance, take a look at our
      Traversing the Document Object Model with JavaScript
      tutorial, our
      How to Modify the DOM with JavaScript
      tutorial, and our
      JavaScript Objects
      tutorial.



      Source link