Connect with us

HOWTO'S

How to Create a Custom WordPress Plugin From Scratch

Published

on

Main Article Image

A theme is required for every WordPress site to pull data from the database and display it in a design. You could theoretically run a site using only a theme. But, this site would be extremely limited without plugins.

WordPress plugins are an extension of WordPress core that adds additional functionality to your site. Plugins can be used to add everything to your WordPress site, from an animated slide or booking calendar to a fully-featured learning management system and online marketplace.

This guide will show you how to make your own WordPress plugin. I will show you best practices in plugin development, how to get your plugin to run, as well as how to organize your plugin’s files and code. You’ll also find some frequently asked questions and a walkthrough of how to create your first plugin.

WordPress plugins available for free and paid

There are many places where you can download or buy plugins to enhance your website. You can find thousands of plugins in the WordPress plugin directory that will help you build the website you want. If you are looking for advanced features, better support or a better user interface, premium plugins can be purchased from CodeCanyon.

Codecanyon%20shortcode%20plugins

Sometimes, however, you may need to create your own plugin. You might not need all the code from third-party plugins, so this can be more efficient. This allows you to create a plugin that suits your needs better, or modify an existing plugin to suit your site.

What are the Essentials to Create a Plugin?

You will need the following:

  • a code editor
  • A development WordPress installation is provided with a copy your live site to test.

Test your plugin only on your live website once you are certain it works.

If you don’t have a WordPress local installation, please follow our guide to copying and installing your site to a local install . If you are unable to install WordPress locally, you can use a backup of your site on your server. Learn how you can copy your site.

Advertisement

Types of WordPress plugins

Many plugins are capable of performing many tasks. They all add functionality to your website. There are many types of WordPress plugins.

  • Site Maintenance Plugins to help with security, backups, and performance
  • Marketing and Sales Plugins For things like SEO, Social Media, or eCommerce
  • Content Plugins including custom post types, widgets and shortcodes, forms, galleries and video feeds
  • API plugins which work with the WordPress API or pull in content from services such as Google Maps
  • Community plugins which add social networking features

You can do so much more! You can get an idea of the potential uses of plugins by looking at the WordPress plugin directory or the CodeCanyon marketplace.

WordPress%20plug in%20directory

What goes into a plugin?

Before you start building your plugin, it is worth understanding what goes into it. The exact look of your plugin’s code will depend on the type of plugin. Some plugins are very small with only one file, while others have multiple files with scripts, stylesheets and template files. There are many plugins that fall somewhere in between.

These are the elements that you will likely have in your plugin:

  • The main plugin file (this is crucial)
  • folders for different file types
  • Scripts
  • Stylesheets
  • Include files to organize the code

Let’s take a closer look at each one.

The Main Plugin File

It is vital to have the main plugin file. It will always be a PHP-file and will always include commented-out text telling WordPress about your plugin.

Here’s an example from Akismet:

<?php
 
/**
 
 * @package Akismet
 
 */
 
/*
 
Plugin Name: Akismet Anti-Spam
 
Plugin URI: https://akismet.com/
 
Description: Used by millions, Akismet is quite possibly the best way in the world to <strong>protect your blog from spam</strong>. It keeps your site protected even while you sleep. To get started: activate the Akismet plugin and then go to your Akismet Settings page to set up your API key.
 
Version: 4.1.7
 
Author: Automattic
 
Author URI: https://automattic.com/wordpress-plugins/
 
License: GPLv2 or later
 
Text Domain: akismet
 
*/

This information tells WordPress about your plugin, its location, who created it, and what it does. It also gives information about the version number and the text domain and path for internationalisation, as well as the license.

WordPress uses this information to populate your plugins screen. This is how Akismet appears on that screen.

Advertisement
Akismet%20in%20the%20plugins%20admin%20screen

As you can see, the information in the plugin file was used to populate the entry and provide links.

Additional information about the plugin can be found in the README.txt file. This file is used to populate plugin’s page in plugin directory.

Akismet%20in%20the%20plugins%20directory

The code that runs the plugin will be found in the main plugin file. Sometimes this will contain all of the PHP needed to run the plugin. However, larger plugins may require additional code to be included in the main plugin file. This allows you to organize your code and makes it easier to use. Later in this guide, I will show you how to use include file.

Folder Structure

Although there aren’t any hard and fast rules about how to organise your folders in your plugins, it is a good idea to follow the same pattern as other plugin developers. This will allow you to familiarize yourself with how other plugins work and will help you communicate your code to others.

Your plugin may contain the following folders:

  • CSS or style to stylesheets
  • scripts JavaScript
  • includes for include files
  • templates to be used in template files.
  • assets to media and other asset file
  • i18n internationalisation files

If your plugin is complex or large, you might need more folders. WooCommerce, for example, has folders to store sample data and packages. These folders contain subfolders that can be used to store admin files and blocks.

WooCommerce%20files

Stylesheets and scripts

Stylesheets are required if your plugin produces content that requires styling. This could be in the admin screens or the front-end. If your plugin uses scripts, stylesheets will be required.

Even if you have only one, it makes sense to keep them in their own folder. These scripts and stylesheets will need to be enqueued using a specific function in your main plugin. This is how I will show you when we build the plugin.

Include Files

Splitting your code into multiple files called include files can help you organize your plugin. These files can then be placed in their own folders and called from your main plugin file with an include, or need function.

This allows you to keep your bulk of code in a well-organized file structure, while your main plugin file is kept small and manageable.

Advertisement

You don’t have to use include files if your plugin is small. Simply add your code to your main plugin file. To maintain a logical structure, you may need to organize the file and reorder functions as you add them.

These are the most commonly used elements in a plugin. As we’ve seen with WooCommerce, there are many other elements. You can also have many smaller plugins. These elements will be more frequently used as you create more plugins.

How to Run Your Plugin Code

Activating your plugin is the first step to enabling it to work. You have a few options to activate your code, or pull in code from WordPress.

  • Functions
  • Action and filter hooks
  • Classes

Let’s take a closer look at each one.

Functions

Functions are the foundation of WordPress code. These functions are the easiest way to start writing your own plugins, and they’re also the most straightforward to code. They’re also found in the themes’ files.

Each function will be given a name and then braces with the code within them.

Your plugin’s code won’t run unless it calls the function. This is the simplest, but least flexible way to do it. You can call the code directly in your theme or elsewhere in your plugin.

Advertisement

Here’s an example of a function:

tutsplus_myfunction {
 
// code goes here
 
}

To directly call that function in your theme, you’d simply type tutsplus_myfunction() in the place in your theme template files where you want it to run. You could also add it to your plugin, but you would need to activate it.

These limitations are:

  • You can’t activate a function that does more than adding content to a theme template file.
  • You will need to call the function again and again if you want it to be called in more than one place.
  • It can be difficult to keep track all the functions you have manually called.

It is a better idea to attach functions to a hook to be able to call them.

Filter and Action Hooks

Attaching your function to an hook allows you to run it whenever the hook fires. There are two types: filter hooks and action hooks.

Action hooks are not useful. WordPress does not respond to action hooks unless it has been connected to a function.

Filter hooks are code that will run , unless there’s a function hooked up to that hook. If there’s a function attached to the hook, it will run that function. You can either add default code to your plugin and override it with another plugin or write a function to override the default code attached to a filter hook within WordPress.

Advertisement

Three ways to fire hooks:

  • WordPress. There are hundreds of hooks in the WordPress core code that can fire at different times. Depending on the function you are hooking, which one you use will determine what you need. The developer handbook contains a list WordPress hooks.
  • Your theme. You can add additional content to key areas of your website’s design by using action and filter hooks. All themes include a wp_footer hook. These can be combined with conditional tags to allow you to run specific code on particular pages within your site.
  • Your plugin and other plugins. An action hook can be added to your plugin. Then, you might include functions in your include files to attach code to the hook. You might also write a filter hook that allows you to override certain functions. You can also hook your functions to an existing hook in a third-party plugin if you are creating a plugin. This is what I did with WooCommerce to customize the output of product pages.

While some of these are more advanced, your first plugin will hook your functions to an action/filter hook output by WordPress, most likely an Action Hook.

Classes

Classes allow you to code more complicated features such as customizer elements and widgets, using the existing WordPress APIs.

You’ll likely be adding a class to your plugin by extending an already-coded class. You can use the code provided by the class to modify it to your liking. You might use the customizer as an example. Here you could write a class that includes a color picker and make use of the color picker interface provided in the existing customizer class.

Classes are more complex than functions and you won’t be able to do it with your first plugin. For more information, please refer to our guide to classes for WordPress.

Even if you write classes, actions and filters will still be required to make them run.

Best Practices for Plugins

It is important to learn best practices before you begin coding your plugin. This will ensure that your code is high-quality right from the beginning.

Advertisement

These include:

  • WordPress coding guidelines will guide you in writing your code. You will need to submit your plugin for inclusion in the plugin directory.
  • Comment your code to make it easier for others to work with. This will help you to remember how it works when you return to it later.
  • Prefix your functions, hooks, or classes with prefixes to make them unique to your plugin. It is not a good idea to name a function the exact same as another function in WordPress core or another plugin.
  • Your folders should be organized logically. Keep your code separate so that others can understand it. Also, so that you can add to it as needed without making it a mess.

It might seem that best practice doesn’t matter if you’re the only one using the plugin. Your plugin may grow over time. You might allow others to use it or sell it. You might forget how it is organized in two years.

In 4 Easy Steps, Create Your First Plugin

At last! Now that you have an understanding of plugins, it is time to get started creating your first plugin. This tutorial will show you how to create a simple plugin that registers custom post types.

This is a common use of a plug-in, and one you can continue to build upon over time to add custom templates files for your post type or other functionality.

I will show you the basics of the plugin, and then give you an overview of how you can add to it.

1. Create the Plugin Folder and File

Even if your plugin starts small, even if it only has one file, it is a good idea to give it its own folder. Create a folder within your WordPress Content/plugins directory. Create a PHP file inside that folder for your plugin.

Both folders should be given a name that is logical and includes a prefix. I’m calling my folder tutsplus-register-post-types and my file tutsplus-register-post-types.php.

Advertisement

Open your plugin file, and then add the commented-out information to the top. Take my example below and modify it to reflect that this plugin is yours.

<?php
 
/*
 
Plugin Name: Tuts+ Register Post Types
 
Plugin URI: https://tutsplus.com/
 
Description: Plugin to accompany tutsplus guide to creating plugins, registers a post type.
 
Version: 1.0
 
Author: Rachel McCollin
 
Author URI: https://rachelmccollin.com/
 
License: GPLv2 or later
 
Text Domain: tutsplus
 
*/

Save your file, then go to the plugins screen on your development site. You’ll see the plug-in there.

New%20plugin%20in%20the%20plugins%20admin%20screen

It can be activated if you wish, but it won’t do anything because you haven’t added any code. Let’s get started.

2. Add Functions

Now, it’s time for the first function to be written in our plugin. Make your plugin by adding the braces that will contain the code. Here is mine:

function tutsplus_register_post_type() {
 
    // movies
 
    $labels = array( 
 
        'name' => __( 'Movies' , 'tutsplus' ),
 
        'singular_name' => __( 'Movie' , 'tutsplus' ),
 
        'add_new' => __( 'New Movie' , 'tutsplus' ),
 
        'add_new_item' => __( 'Add New Movie' , 'tutsplus' ),
 
        'edit_item' => __( 'Edit Movie' , 'tutsplus' ),
 
        'new_item' => __( 'New Movie' , 'tutsplus' ),
 
        'view_item' => __( 'View Movie' , 'tutsplus' ),
 
        'search_items' => __( 'Search Movies' , 'tutsplus' ),
 
        'not_found' =>  __( 'No Movies Found' , 'tutsplus' ),
 
        'not_found_in_trash' => __( 'No Movies found in Trash' , 'tutsplus' ),
 
    );
 
    $args = array(
 
        'labels' => $labels,
 
        'has_archive' => true,
 
        'public' => true,
 
        'hierarchical' => false,
 
        'supports' => array(
 
            'title', 
 
            'editor', 
 
            'excerpt', 
 
            'custom-fields', 
 
            'thumbnail',
 
            'page-attributes'
 
        ),
 
        'rewrite'   => array( 'slug' => 'movies' ),
 
        'show_in_rest' => true
 
    );
 
}

This includes all of the arguments and labels for your post type, and (crucially), the register_post_type() function that is provided by WordPress.

As I am creating a movie review website, I have used movies as my post type. You may want to try something else.

You’ll notice that nothing has changed if you save the file and then go back to your website. This is because your code has not been activated. We activate the function by hooking it up to the init hook, which is provided by WordPress. You can use the function provided by WordPress (e.g register_post_type), but there is a hook you should use. Details can be found in the WordPress handbook entry Registering custom post types.

Advertisement

Let’s now add the hook. Add the following line to your code.

add_action( 'init', 'tutsplus_register_post_type' );

To hook our code to an Action Hook, we use the Add_ACTION() function. It has two parameters: The name of the action hook as well as the name our function.

Save your files now and go back to your website. If you activated the plugin, you will see the custom post type in your admin menu.

New%20post%20type%20in%20admin%20menu

It’s great!

Let’s now add an additional function to register a custom taxonomy. Add this to the code that you have written so far:

function tutsplus_register_taxonomy() {    
      
    // books
    $labels = array(
        'name' => __( 'Genres' , 'tutsplus' ),
        'singular_name' => __( 'Genre', 'tutsplus' ),
        'search_items' => __( 'Search Genres' , 'tutsplus' ),
        'all_items' => __( 'All Genres' , 'tutsplus' ),
        'edit_item' => __( 'Edit Genre' , 'tutsplus' ),
        'update_item' => __( 'Update Genres' , 'tutsplus' ),
        'add_new_item' => __( 'Add New Genre' , 'tutsplus' ),
        'new_item_name' => __( 'New Genre Name' , 'tutsplus' ),
        'menu_name' => __( 'Genres' , 'tutsplus' ),
    );
      
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'sort' => true,
        'args' => array( 'orderby' => 'term_order' ),
        'rewrite' => array( 'slug' => 'genres' ),
        'show_admin_column' => true,
        'show_in_rest' => true
  
    );
      
    register_taxonomy( 'tutsplus_genre', array( 'tutsplus_movie' ), $args);
      
}
add_action( 'init', 'tutsplus_register_taxonomy' );

You might also want to modify the name of your custom taxinomy. Here, the taxonomy is applied to the post type that I just registered (the third parameter in the register_taxonomy operation). You can edit the bit if you gave your post type another name.

Save your file now and go to your admin screens. The new taxonomy will be visible if you hover over the post type in your admin menu.

Advertisement

Now you have a working plugin. Well done!

Let’s look at what you can do to make it better.

3. Enqueue Stylesheets and Scripts

You can add custom styling and scripts to your plugin files if you have the need. However, this is not the best practice. Instead, create stylesheets or scripts in separate files within your plugin folder, and then enqueue them using a WordPress function.

Let’s say you want to add styling to your custom post type. This could be added to your theme. However, you may want to add specific styling to the plugin in order to make the custom post type stand out from all other types of post types.

You will need to create a folder in your plugin folder named CSS or styles. You can name your stylesheet style.css or give it a specific name to make it easier to find. My movies.css.

The file must be enqueued in your plugin to allow WordPress to use it. This should be added to the main plugin file. Enqueuing and include are important to me. This allows me to see which files are being activated.

function tutsplus_movie_styles() {
    wp_enqueue_style( 'movies',  plugin_dir_url( __FILE__ ) . ‘/css/movies.css’ );                      
}
add_action( 'wp_enqueue_scripts', ‘tutsplus_movie_styles' );

You won’t notice any changes in your admin screens if you save your file. However, if you have added custom post types and your stylesheet includes styling, you will now see them in the front-end.

Advertisement

The hook for enqueuing stylesheets and scripts are the same. They both use wp_enqueue_scripts. There is no separate hook for styles.

The same way that Enqueuing scripts work is for query scripts. These are the steps to follow:

  • To your plugin folder, add a scripts and js directory.
  • There are script files that you can save.
  • You can now queue the script the same as the stylesheet, substituting the style() function by Enqueue_script()

4. Use Include Files

You can also create additional PHP files as part of your plugin development. These are known as include files. You might have multiple include files, so you could create several folders or one folder named includes.

You can use a few functions to include files. These functions are covered in our comprehensive guide to including requiring files.

We might, for example, create code in our custom plugin to change the output of the page’s content. This could be done by using the the_content filter hook. The code will then be modified each time that the product page displays the content.

You could instead of adding the code to the main plugin folder, create a separate movie-content.php file and then add the code there to control the output for movies.

You add the content-movie.php folder to your plugin in order to include this file.

Advertisement

This code is needed to include the file in your plugin.

include( plugin_dir_path( __FILE__ ) . ‘includes/movie-content.php' );

This doesn’t have to be hooked to any action or filter hook. Just use the include_once() function within your plugin file. This will call the code in the include file just like it was in the main plugin file.

How to extend or edit an existing plugin

Sometimes, you may find a plugin from a vendor or in the plugin directory that does all you need. You might also want to tweak or customise a plugin.

WordPress is open-source makes it possible. It is possible to take the code of another plugin and modify it to make it function as you wish.

Two ways to accomplish this are available:

  • Fork an existing plugin, i.e. Edit it to make it more reliable or work differently.
  • Create your plugin to extend the original plugin.

Editing an existing plugin is easy: You create your own copy on a site that you have created (never live!) You can make changes to the plugin as necessary. To avoid any problems, make sure to use version control.

Although it is more difficult to extend a plugin using your own plugin, it is more reliable.

Advertisement

Hooks and classes are a common feature of popular plugins. Hook into action and filter hooks, and extend classes to create your own code. This code uses an existing plugin’s base code but adds or changes it.

WooCommerce, for example, has many functions, hooks and classes. It even has its own API. These functions, hooks, and classes power every part of WooCommerce. You must identify the code that is driving the WooCommerce system, then create your plugin to attach to it or extend the classes.

This is how you can customize a plugin such as WooCommerce. I used it once to power a listing site without a checkout. Hooks were used to remove unwanted elements and create new ones.

You can hook into WooCommerce to extend it or add your own plugin. See our guides to adding product description to archive pages, and to adding product-based blogs to your store. These are just a few examples of what you can do, but they will give you an idea of where to begin.

Take It Further: Plugin Features

This guide will show you how plugins work and how to start building your own plugin.

Once you are proficient in plugin development, you will be able to create more complicated and fully-featured plugins that can perform more complex tasks for your site.

Advertisement

Let’s look at some examples.

Widget Plugins

Although widget plugins require you to work with classes, they are a great introduction to the topic. This guide will show you how to create a widget plugin.

CodeCanyon also offers many widget plug-ins, which can be used to save time and effort in coding. We’ve identified the top widget plugins for 2021 and the best Facebook widgets as well as the most useful Twitter widgets.

Code%20Canyon%20widget%20plugins

Shortcode plugins

A shortcode is an excellent place to begin creating plugins. They are simple and extremely useful. Learn how to create them in our coding guide for WordPress.

CodeCanyon also offers a number of shortcode plugins that you can use to enhance your website’s functionality.

Code%20Canyon%20shortcode%20plugins

Social Media Plugins

Social media plugins are extremely popular because they allow you to display your Instagram, Twitter, and Facebook feeds on your website, and allow your visitors to share your content through their social media accounts.

CodeCanyon offers many social-media plugins. Find out which social media plugins are the best and how to build an online community for WordPress.

Gallery and Media Plugins

A plugin can make your site look professional and optimise your media. Learn how to create your own gallery plugin. You can also browse the professional gallery or video plugins at CodeCanyon.

Advertisement
media%20plugins%20on%20Code%20Canyon

Form Plugins

Your visitors can contact you by adding forms to their site. This helps them build a connection. CodeCanyon offers many premium forms plugins to make it easier for visitors to get in touch with you. Learn how you can create a form using the popular QuForm plugin.

Summary

Plugins can transform your website from a blog to a robust, secure, and robust website. To improve your WordPress website, you can add plugins to your site or code your own.

The Best WordPress Themes and Plugins on Envato Market

Explore thousands of the best WordPress themes ever created on ThemeForest and leading WordPress plugins on CodeCanyon. Purchase these high-quality WordPress themes and plugins and improve your website experience for you and your visitors.

themeforest%20popular%20wordpress%20themes

First seen at Tutsplus.com

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address

AFFILIATE MARKETING

How to Add Affiliate Disclosure for Each Blog Post Automatically

Published

on

How to add affiliate disclosure for each blog post automatically

Do you want to add an affiliate disclosure for each blog post automatically?

Affiliate marketing is one of the easiest ways to make money online. However, if you don’t disclose your affiliate links then you could end up in legal trouble.

In this article, we will show you how you can add an affiliate disclosure to all your WordPress blog posts.

Why Add an Affiliate Disclosure to Each WordPress Blog Post?

With affiliate marketing, you earn a commission every time someone clicks a referral link and makes a purchase. It’s a great way to make money online blogging with WordPress.

However, you must make it clear that your links are paid advertisements by adding an affiliate disclaimer. That just means posting a short notice explaining what affiliate marketing is, and that you get money from talking about the product or service.

Many countries have laws about failing to disclose paid endorsements. For example in the United States, you might get a fine from the Federal Trade Commission. You may even end up banned from reputable networks such as Amazon affiliates.

Even if you don’t get into legal trouble, customers who click on undisclosed affiliate links may feel tricked and stop visiting your WordPress website.

Advertisement



How to Add an Affiliate Disclosure to Each WordPress Blog Post

One option is to publish the affiliate disclaimer on its own page, as we do on WPBeginner.

The WPBeginner affiliate disclaimer page

You can then add a link to every page that features an affiliate URL. This may be a good choice if you have a longer disclosure and don’t want to distract from the post’s content.

If yours is short, then you can often add the full text of the disclaimer to every post.

An example affiliate disclaimer on a blog

No matter which option you choose, you can save time and effort by adding the affiliate disclosure automatically. Simply use the quick links below to jump straight to the method you want to use.

Pretty Links is one of the best affiliate marketing plugins that can automate all your affiliate activities, including adding a disclosure.

Pretty Links comes with an advanced auto-linking feature that allows you to enter the keywords or phrases that you want to turn into affiliate URLs.

Every time you type this word or phrase, Pretty Links will turn it into an affiliate URL automatically. Even better, if you have created a disclosure notice page, Pretty Links can also add a link to it in the post.

For example, if you add “MacBook Pro” as a keyword and then use that phrase in a new post, then Pretty Links will automatically turn “MacBook Pro” into an affiliate URL and add a link to your disclosure notice page.

Advertisement



An affiliate disclaimer, created using Pretty Links

Note: Pretty Links won’t insert the disclosure link if you only add affiliate URLs manually. It only works when a post uses automatic keyword linking.

To get started, you’ll need to install and activate Pretty Links. If you need help, then please see our guide on how to install a WordPress plugin.

Upon activation, go to Pretty Links » Activate. You can then add your license key to the following field: ‘Enter Your Pretty Links Pro License Key.’

Activating the Pretty Links WordPress plugin

You can find this information under your account on the Pretty Links website. After typing in this information, click on the ‘Activate’ button.

With that done, you’ll need to go to Pretty Links » Add New and then add the first link you want to manage using the Pretty Links plugin.

For detailed step-by-step instructions, please see our guide on how to cloak affiliate links on your WordPress site.

How to cloak an affiliate link in WordPress with Pretty Links

After that, click on the ‘Pro’ tab. In the ‘Keywords’ field, type in each word or phrase where you want to automatically insert this affiliate URL.

Simply repeat this process for all your affiliate links.

Adding keywords to the Pretty Links affiliate linking plugin

Every time it adds this affiliate URL, Pretty Links will also add a link to your disclosure notice.

The next step is creating the disclosure notice page that Pretty Links will link to. Simply go to Pages » Add New. You can then type in your affiliate disclaimer and add any categories or tags that you want to use.

Advertisement



An example affiliate disclaimer

When you’re happy with your disclaimer, publish the page to make it live. It’s a good idea to make a note of the page’s URL, as you’ll need it in the next step.

Once you’ve done that, simply go to Pretty Links » Options. Then, click on the ‘Replacements’ tab.

Pretty Links' auto-linking and replacement settings

Here, check the ‘Enable Replacements’ box if it isn’t already selected.

After that, check the ‘Link to Disclosures’ box. In the ‘URL’ box, go ahead and enter your affiliate disclosure URL.

Pretty Links Disclosure Notice

By default, Pretty Links will use ‘Affiliate Link Disclosures’ as your link’s text. However, you can change this to anything you want by typing into the ‘Text’ field.

You can also change where Pretty Links adds the affiliate disclaimer link. By default, it shows the URL at the bottom of the post, so it doesn’t distract visitors from the post’s content.

Another option is to add the disclaimer to the top of the post. This is where we include it on WPBeginner.

WPBeginner Disclosure Notice

This lets visitors know the post contains an affiliate link before they start reading, which is a good way to build trust with your audience. However, some people may see the disclaimer and decide not to stay on the page, which can increase your bounce rate.

You can also add the disclaimer to both the top and bottom of each post. This may be a good idea if you write very long posts, but most sites don’t need multiple disclosures per page.

To place the affiliate URL, simply open the ‘Position’ dropdown and choose Bottom, Top, or Top and Bottom.

Advertisement



Changing where an affiliate disclaimer appears on your WordPress website

Once you’ve done that, just scroll to the bottom of the page.

Then, click on the ‘Update’ button.

Saving your Pretty Links settings

Now, Pretty Links will add an affiliate disclosure link every time it auto-inserts an affiliate URL to your posts, pages, or custom post types.

Method 2. Add Affiliate Disclosure Using WPCode (More Customizable)

Sometimes you may want to add the affiliate disclosure to different areas of every blog post. For example, you might show the disclosure after you mention each affiliate product for the first time.

In this case, you can create a shortcode that adds your affiliate disclaimer. This gives you complete control over where the disclosure appears, without you having to type the entire text every single time.

A custom shortcode created with WPCode

The easiest way to create a custom shortcode is using WPCode. This plugin lets you add code snippets to WordPress without editing your theme’s functions.php file.

WPCode also helps you avoid common errors by performing smart code snippet validation.

There are lots of ways to add an affiliate disclosure using WPCode. Besides the shortcode method, we’ll also share an easy way to automatically add the disclaimer to every post, page, or custom post type.

The first thing you need to do is install and activate the free WPCode plugin on your website. For more details, see our step-by-step guide on how to install a WordPress plugin.

Advertisement



Upon activation, go to Code Snippets » Add Snippet.

Adding a custom code snippet to WordPress

This will bring you to the ‘Add Snippet’ page where you can see all the ready-made snippets that you can use on your site.

Since we want to add custom code in WordPress, hover your mouse over ‘Add Your Custom Code (New Snippet).’ Then, click on ‘Use snippet’ when it appears.

Adding custom snippets to WordPress

To start, enter a title for the custom code snippet.

This could be anything that helps you identify the snippet in the WordPress admin area.

Adding a title to a WPCode custom code snippet

We’re going to add a PHP snippet, so open the ‘Code Type’ dropdown and choose the ‘PHP Snippet’ option.

You can then go ahead and paste the following code into the code box:

function disclosure() {
    return "<p class="disclosure">This site may contain links to affiliate websites, and we receive an affiliate commission for any purchases made by you on the affiliate website using such links.</p>";
}

add_shortcode( 'disclosure', 'disclosure' );

You can use any text as your affiliate disclaimer, simply by editing the code above. For example, you might want to add a link in HTML to your affiliate disclosure page.

Once you’ve done that, scroll to the ‘Insertion’ section and make sure ‘Auto Insert’ is selected.

Advertisement



Auto-inserting custom code snippets in WordPress

Then, open the ‘Location’ dropdown and choose ‘Frontend Only’ since we only want to use this code on our site’s frontend, which is what visitors see when they visit your site.

You can also organize your snippets by adding tags.

When you’re happy with how the snippet is set up, scroll to the top of the screen and click on ‘Save Snippet.’

Saving your WPCode snippet

After that, you can make the code snippet live by clicking the ‘Active’ toggle.

Finally, don’t forget to save the change by clicking on ‘Update.’

Updating a custom code snippet in WordPress

Now you can add the affiliate disclosure to any page, post, or custom post type using the [disclosure] shortcode. For more details on how to place the shortcode, you can see our guide on how to add a shortcode in WordPress.

How to Automatically Display the Affiliate Disclosure with WPCode

With WPCode, there are lots of different ways to add an affiliate disclosure to your WordPress website, including automatically adding it to every post.

This can save you a lot of time and effort, since you don’t need to add the shortcode manually. However, the disclosure will appear in the same location on every page.

Advertisement



To automatically add the disclaimer, simply create a new custom code snippet by following the same process described above. However, this time open the ‘Code Type’ dropdown and select ‘HTML Snippet.’

Adding an HTML snippet to WordPress

You can now add your disclaimer in the code editor, complete with the formatting that you want to use. For example, here we’re adding a simple disclaimer as a new paragraph:

<p>This site may contain links to affiliate websites, and we receive an affiliate commission for any purchases made by you on the affiliate website using such links.</p>

Next, scroll to the ‘Insertion’ section and open the ‘Location’ dropdown.

You can now choose where this disclaimer should appear, such as ‘Insert After Post’ or ‘Insert Before Content.’

Automatically inserting an affiliate disclaimer

You can then go ahead and enable the snippet by following the same process described above. WPCode will now automatically show the disclaimer on every page, post, and custom post type, without you having to add the shortcode manually.

Method 3. Add Affiliate Disclosure Using Full-Site Editor (Block-Enabled Themes Only)

If you’re using a block-based theme like Hestia Pro, then you can add an affiliate disclosure to your theme’s blog post template.

This is a good choice if you want to show the exact same disclosure on every blog post. However, you won’t have the option to change the style or text on individual posts, so it’s not a good choice if you want to show different information on different pages.

To use this method, go to Themes » Editor in the WordPress dashboard.

Advertisement



Opening the WordPress full-site editor (FSE)

By default, the full-site editor will show your theme’s home template, so you’ll typically want to select a new template.

If you want to show the affiliate disclosure across your entire website, then we recommend adding it to the footer template part. 

However, if you just want to show the disclaimer on your blog posts, then click on Templates on the left-hand side of the screen in the Design section.

Adding an affiliate disclosure using the full-site editor (FSE)

The editor will now show all the layouts that make up your WordPress theme.

Simply click go ahead and click on ‘Single.’

Adding an affiliate disclaimer to a WordPress blog post template

WordPress will now show a preview of the template.

To edit this template, go ahead and click on the small pencil icon.

Editing a blog post template in a block-enabled WordPress theme

With that done, click on the blue ‘+’ icon in the top left corner.

In the search bar that appears, type in ‘Paragraph’ to find the right block. 

Adding a Paragraph block to a full-site template

You can now drag and drop the block onto the area where you want to show the disclaimer. 

Now, click on the block and type in your affiliate disclaimer. 

Advertisement



Adding text to a WordPress blog template

You may also want to change how the disclaimer looks. 

To change the font size, background color, and more, simply click to select the paragraph block. Then, select the ‘Block’ tab in the right-hand menu.

Styling affiliate disclaimers using the WordPress FSE block-based editor

You can now change the background color and text color, or make the disclaimer bigger or smaller using the settings in the right-hand menu.

When you’re happy with how the disclaimer looks, click on the ‘Save’ button.

An example of an affiliate disclaimer, created using the FSE

Now, if you visit any blog post on your affiliate website, you’ll see the disclaimer in action. 

We hope this article helped you learn how to add affiliate disclosures for each blog post automatically. You can also go through our guide on the best giveaway and contest plugins and how to create an email newsletter the RIGHT way.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.



Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

HOWTO'S

What a 500 Internal Server Error is, and How to Fix it

Published

on

What a 500 Internal Server Error is, and How to Fix it

No one likes opening a webpage and seeing a 500 internal server error message—especially when it’s on your own website.

The problem with seeing this is the mystery behind it: a 500 internal server error is a very general HTTP status code with no definitive clues as to what is causing it. 

If you’re seeing one now and are stumped, don’t worry. We can help you find what’s wrong, and what you need to do to fix it.

What is a Website Status Code?

Also known as a HTTP status code, these are a series of numbers that equates to a certain status of a webpage that you are currently viewing.

Whenever you visit a website, your browser sends a request to its server. The server then processes it, and sends back the resources needed to load whichever page you’re requesting. Attached to that is an HTTP header as well as a status code. 

If everything can load fine, that status code is a 200. If there’s something wrong, it could be a 500 status code.

Advertisement



Webmaster’s Note: This is part of our more comprehensive guide to Technical SEO, where I cover everything you need to know about crawlability, indexing, and page speed optimization, as well as helpful tips on how to troubleshoot common website errors. 

What are 500 Internal Server Errors?

The 500 Internal Server Error, also known as HTTP Error 500, is a server response that indicates an unexpected problem preventing the server from fulfilling the user’s request. 

In simpler words, it’s a general message from your server saying “There’s a problem, but I’m not sure what.” 

500 Internal Server Error

So if you’re seeing one now, then it is important to understand that the issue is not due to the user’s browser, internet connection, or device. Instead, the problem lies with the server that hosts the website. This server-side error can manifest in various messages, as different websites may display their own variations of the 500 error.

Here are some of the different variations of the 500 Internal Server Error:

  • 500 Internal Server Error
  • Internal Server Error 500
  • HTTP Error 500
  • HTTP Status 500 – Internal Server Error
  • Error 500 Internal Server Error
  • 500 Error
  • Temporary Error (500)
  • 500 – Server Error
  • The website cannot display the page – HTTP 500.

Causes of 500 Internal Server Errors

The generic 500 server error can be challenging to pinpoint, because it is a general error—it does not point to any specific cause from the get-go. This means you have to dig into your website to find the cause. 

But the good news is there are some likely culprits you can look at first:

Advertisement



  • Browser Cache: Clearing your browser cache can help resolve the issue by ensuring that you are accessing the most up-to-date version of the website.
  • Database Issues: Incorrect login credentials or a corrupt database can trigger a 500 error. Double-check that the credentials are correct and consider repairing or optimizing the database.
  • Corrupted Files: If the core files of a WordPress website become corrupted, it can lead to a 500 error. Restoring or updating these files can help resolve the issue.
  • Server and Disk Space: Issues within the server, such as running out of disk space or PHP memory limit exhaustion, can result in a 500 error. Contact your hosting provider to address these server-related issues.
  • File Permissions and .htaccess: Incorrect file or folder permissions, as well as a corrupt or broken .htaccess file, can cause a 500 error. Double-check these settings and make necessary adjustments.
  • Third-Party Plugins and Themes: Compatibility issues or errors within third-party plugins or themes can trigger a 500 error. Disable or remove these elements one by one to identify the problematic ones.
  • Malware infections: Malicious software can compromise your website’s functionality and trigger internal server errors. For example, if a hacker injects a piece of malicious code into your website’s files, it can disrupt the server’s operation and result in a 500 error.
  • Broken script injections: Hackers can inject malicious scripts into your website’s code, which may cause conflicts and result in internal server errors.

By understanding these potential causes, you can take the necessary steps to address them and resolve the 500 internal server errors. 

Troubleshooting 500 Internal Server Errors

To resolve 500 internal server errors and get your website back online, you could follow these detailed troubleshooting steps:

Clear Your Browser Cache 

Clearing your cache can resolve a 500 Internal Server Error

Before diving into complex troubleshooting steps, clearing your browser cache is a good starting point. By clearing the cache, you ensure that any previously stored data or cached versions of the website are removed, allowing for a fresh attempt at accessing the site.

This can be especially helpful if the error was caused by a previous version of the website being cached locally on your device.

  • Example: Let’s say you are using Google Chrome. To clear your browser cache, you would click on the three dots icon at the top right of the browser window, go to “More tools,” select “Clear browsing data,” choose a time range or “All time” option, and finally, click “Clear data” to remove the cached files.

Reload the Page 

After encountering a 500 error, it is worth waiting a minute and then attempting to reload the page. 

The error can be temporary if it occurs due to server overload or maintenance. By reloading the page, you give the server a chance to resolve the issue and send a proper response.

  • Example: You visit a news website and encounter a 500 internal server error while trying to access an article. Instead of immediately assuming a problem with your device, you wait for a moment and then press F5 or Ctrl + F5 to refresh the page. If the server overload was the cause, the website would likely be accessible again after the reload.

Check for Recently Installed or Updated Software 

If the 500 error persists, it is important to investigate whether any recently installed or updated software on your website may be causing conflicts. 

This could include plugins, themes, or any other website components that have undergone changes.

  • Example: You recently updated the content management system (CMS) of your WordPress website, and shortly after, you start experiencing 500 Errors. To troubleshoot the issue, you can compare the date of the CMS update with the start of the errors. If they align, it may indicate that the update caused compatibility issues or conflicts with other plugins or themes.

Check for Server-side Errors

Review your server’s error logs to identify any specific error messages or patterns. These logs can provide valuable insights into the underlying issues causing Error 500.

  • Example: A server error log indicating database connection failures may indicate a misconfiguration in your website’s database settings, leading to 500 internal server errors.

Review Error Logs

Check and review the server's error logs to fix an 500 Internal Server Error

Look for recurring errors or warnings that may indicate underlying issues. Correlate timestamps with user-reported errors if applicable to pinpoint specific areas of concern.

Advertisement



  • Example: If users consistently report a 500 error when submitting a contact form, reviewing error logs during those instances may reveal issues with the form submission script.

Identify and Fix .htaccess File Issues

Open the .htaccess file using a text editor and check for syntax errors or conflicting directives. Rectify any mistakes or consider renaming the file to regenerate it.

  • Example: A website experiencing Error 500 after adding rewrite rules to the .htaccess file may have introduced syntax errors that disrupt the server’s operation.

Address Script Injection Problems

Inspect your website’s files and code for any suspicious or unrecognized scripts. Remove any injected code and ensure that your website’s security measures are robust.

  • Example: If your website allows user-generated content and you notice unexpected scripts in certain posts or comments, it is possible that malicious users have injected their own code.

500 Error VS. Other 5xx Response Codes

Common 5xx Response Codes

If you’re seeing an error screen and none of these solutions worked, then you might be dealing with a different kind of 5xx error. 

To have a better understanding of the differences between generic 500 errors and other internal server errors, it’s essential to know the most common 5xx response codes:

  • 500 Error: This code indicates that the server encountered an unexpected problem that prevents it from fulfilling the request. It’s an unidentified issue without providing additional details.
  • 501 Error: A “not implemented” HTTP status code, it shows that the server is unable to execute the request. This may happen due to an inability to identify the request’s objective or insufficient power to fulfill it.
  • 502 Error: Known as a “bad gateway,” this response happens when an invalid response is detected by the server acting as a proxy or gateway. This means that the server received an invalid response from an upstream server, potentially indicating a problem with your server if you are using a web application firewall.
  • 503 Error: Happens when a service is unavailable, which can be triggered by server overload, maintenance, or even a malware attack. The server is unable to handle additional tasks at that moment.
  • 504 Error: A “gateway timeout” indicates that the server, operating as a proxy or gateway, was unable to identify the request within the specified time limit.
  • 505 Error: This error happens when the server cannot recognize the HTTP protocol used in the request.
  • 511 Error: An error for network authentication. This means that the server requires user authentication to access the requested resource.

How 500 Error Codes Can Impact Your SEO

Encountering frequent 500 internal server errors can have several negative implications for your website’s SEO:

  • User Experience and Rankings Internal server errors can significantly impact user experience, leading to a low engagement rate as visitors encounter a non-functioning website. User experience is a critical signal for search engines, as they aim to provide the most relevant and satisfying results to users. High bounce rates and decreased engagement can signal to search engines that the website may not be meeting users’ needs, potentially impacting its SEO rankings.
  • Crawling and Indexing – Search engine crawlers could also encounter Error 500 as they attempt to access and index website content. If search engines repeatedly encounter these server errors during crawling, they may interpret it as a sign of poor website maintenance or technical issues. This can result in difficulty for search engines in indexing and ranking the site effectively. It also means that fresh content updates or changes may not be properly discovered or reflected in search results.
  • Domain Authority and Reputation – A website that frequently experiences internal server errors can have a negative impact on its authority and reputation, both in the eyes of search engines and users. 

If a site consistently delivers a poor user experience due to server errors, users may lose trust and credibility in the website. Search engines prioritize user satisfaction and may accordingly adjust rankings for websites that consistently provide a subpar experience. That’s why I consider engaging in ongoing technical SEO a must for any webmaster or SEO professional.

How to Prevent 500 Internal Server Errors

To minimize the risk of future 500 Internal Server Errors, implement these preventive measures:

Regularly Update and Maintain your Website

Keep your content management system (CMS), plugins, and themes up to date to prevent conflicts or vulnerabilities.

Remove any unused or outdated plugins or themes that may create conflicts or security vulnerabilities.

  • Example: An e-commerce website should regularly update its CMS, such as WordPress, along with the associated plugins, to ensure that security vulnerabilities are patched and compatibility issues are avoided.

Implement Reliable Security Measures:

Install a reputable security plugin to protect your website from potential attacks and malware infections. Use strong, unique passwords for administrative access and enable two-factor authentication whenever possible.

If you’re using WordPress, here’s how to scan your WordPress site for better security and to prevent any malicious code.

Advertisement



  • Example: Utilize a security plugin that can actively scan your website for vulnerabilities, block suspicious IP addresses, and provide real-time alerts for potential threats.

Backup your Website Regularly:

Establish a regular backup routine to ensure that you have a clean copy of your website to restore in case of issues or errors.

Store backups in secure off-site locations or use a reliable backup service.

  • Example: Use backup plugins or backup your website manually by downloading both your website files and database, then store the backups on a secure cloud storage platform or external hard drive.

Key Takeaway

Encountering a 500 internal server error can be a frustrating experience, but by understanding its causes and following the troubleshooting steps outlined in this article, you can effectively resolve these issues and minimize their impact on your website and SEO

Prioritize regular maintenance, implement reliable security measures, and establish a backup routine to lessen the chances of having to deal with 500 Internal Server Errors.

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

HOWTO'S

How to Launch a Newsletter on WordPress.com

Published

on

By

How to Launch a Newsletter on WordPress.com

A brand new course to help you successfully launch your newsletter. No registration required and it doesn’t cost a thing.

Unleash your inner creator! Dive into the exciting journey of crafting captivating newsletters with WordPress.com’s newest course: Newsletters 101: From Basics to Automation and Monetization

This completely free online course is designed to share the key skills of creating, managing, and monetizing your newsletter. Whether you’re a blogger, entrepreneur, or part of a non-profit organization, this is your gateway to reaching the hearts and minds of your audience directly in their inboxes.

Let’s dive in!

The power of newsletters

Newsletters offer creators and businesses a unique advantage: a simple way to establish a personal, direct line of communication with their audience, free from the whims and distractions of social media algorithms. Publishing a newsletter can help you forge stronger relationships with your subscribers, nurturing a loyal following over time.

And newsletters are an invaluable tool for generating revenue, too. People who sign up for your newsletter are much more likely to be interested in what you have to offer, which means they’re more receptive to your ideas, recommendations, and products.

Advertisement



Get set up for success

In this course we’ll walk you through the basics of setting up a newsletter, even if you don’t have a website. And if you already have a website you’d like to turn into a newsletter, we’ll also guide you on how to do so with just a few clicks. 

Our Newsletters 101 course will get you started with what you need no matter where you’re at or what your niche is. You’ll find pro tips, ideas, how-tos, and resources for getting the most out of your newsletter. 

The best part? The course is free and no registration is required. Just click the button below and get started!

Unleash your monetization potential

Want to make money through your newsletter? We’ve got you covered! We’ll walk you through setting up paid subscriptions, so you can start generating recurring revenue by simply sharing what you’re passionate about. 

We’ll also explore affiliate marketing, a way to earn commissions through carefully curated product recommendations. Plus, we’ll guide you on integrating ads or sponsored content, offering a win-win scenario where your audience benefits from valuable content, and you earn from your efforts.

Making it real

You might be thinking, “I’m not a techie, can I really do this?” Absolutely, yes! In this course, we break down everything into bite-sized pieces, making it simple to follow along, no matter your technical abilities.

Advertisement



And to support you on the way, we have an Education Community Forum where you can ask questions and celebrate your progress. 

See you there!

PS: Get the best out of our learning resources by checking out all of our courses, live webinars, and recorded replays


Join 100,487,100 other subscribers

Source link

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address
Continue Reading

Trending