How to Create a WordPress Child Theme (Beginner’s Guide)

Do you want to create a child theme in WordPress?

A child theme is a WordPress theme that inherits the functionality of another WordPress theme. Many users create a child for their current theme so that they can safely customize their website design without losing changes when the theme developer releases an update.

In this article, we will show you how to create a child theme for your WordPress site.

How to Create a WordPress Child Theme

How Does a Child Theme Work, and Why Do You Need It?

A child theme inherits all the features, functions, and styles of another WordPress theme. When you create a child theme, the original theme is called the parent theme.

The inheritance includes the parent theme’s style.css file, which defines the theme’s main style. The child theme can override or extend its inherited properties by adding its own files or by modifying the existing ones.

While it is possible to customize your WordPress theme without installing a child theme, there are several reasons why you may need one anyway:

  • Child themes protect your customizations during theme updates, keeping them safe from being overwritten. If you modify the parent theme directly, then those tweaks might vanish when you update.
  • Child themes let you safely try out new designs or features without messing up the site’s original theme, similar to a staging environment.
  • If you know how to code, then child themes can make the development process more efficient. A child theme’s files are much simpler than a parent theme’s. You can focus on modifying only the parts of the parent theme that you want to change or expand on.

What to Do Before Creating a WordPress Child Theme

We’ve seen lots of WordPress users excited to dive into the technical stuff, only to get discouraged when errors pop up. We get it. That’s why it’s important to know what you are getting into before creating a child theme.

Here are some things we recommend you do first before continuing with this step-by-step guide:

  1. Be aware that you will be working with code. At the very least, you will need a basic understanding of HTML, CSS, PHP, and, optionally, JavaScript to understand what changes you need to make. You can read more about this in the WordPress theme handbook.
  2. Choose a parent theme that has your desired website design and features. If possible, find one where you only need to make a few changes.
  3. Use a local site or a staging site for theme development. You don’t want to create unintentional errors on your live site.
  4. Back up your website first.

There are several ways to create a child theme out of your existing theme. One is with manual code, while others require a plugin, which is a lot more beginner-friendly.

The first method may seem intimidating if you lack technical experience. That said, even if you choose one of the plugin methods, we still recommend reading through the manual method to familiarize yourself with the process and the files involved.

Pro Tip: Want to customize your theme without creating a child theme? Use WPCode to safely enable new features with custom code snippets without breaking your website.

With all that in mind, let’s get to how to create a child theme in WordPress. You can jump to the method you prefer using the links below:

Method 1: Creating a Child WordPress Theme Manually

First, you need to open /wp-content/themes/ in your WordPress installation folder.

You can do this by using your WordPress hosting’s file manager or an FTP client. We find the first option to be much easier, so we will use that.

If you are a Bluehost client, then you can log in to your hosting account dashboard and navigate to the ‘Websites’ tab. After that, click ‘Settings.’

Bluehost site settings

In the Overview tab, scroll down to the ‘Quick Links’ section.

Then, select ‘File Manager.’

Bluehost File Manager button

At this stage, you need to go to your website’s public_html folder and open the /wp-content/themes/ path.

Here, just click the ‘+ Folder’ button in the top left corner to create a new folder for your child theme.

Creating a new folder in Bluehost file manager

You can name the folder anything you want.

For this tutorial, we will just use the folder name twentytwentyone-child as we will use Twenty Twenty-One as our parent theme. Once done, just click ‘Create New Folder.’

Naming a new child theme file in Bluehost file manager

Next, you must open the folder you just made and click ‘+ File’ to create the first file for your child theme.

If you use an FTP client, then you can use a text editor like Notepad and upload the file later.

Creating a new file in Bluehost file manager

Go ahead and name this file ‘style.css’ ,as it is your child’s main stylesheet and will contain information about the child theme.

Then, click ‘Create New File.’

Creating a new stylesheet file in Bluehost file manager

Now, just right-click on the style.css file.

After that, click ‘Edit’ to open a new tab like in the screenshot below.

Editing a style.css file in Bluehost file manager

In this new tab, you can paste the following text and adjust it based on your needs:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

Once done, just click ‘Save Changes.’

Saving a stylesheet file in Bluehost file manager

The next thing you need to do is create a second file and name it functions.php. This file will import or enqueue the stylesheets from the parent theme’s files.

Once you’ve created the document, add the following wp_enqueue code:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
    $parenthandle = 'twenty-twenty-one-style'; // This is 'twenty-twenty-one-style' for the Twenty Twenty-one theme.
    $theme = wp_get_theme();
    wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css', 
        array(), // if the parent theme code has a dependency, copy it to here
        $theme->parent()->get('Version')
    );
    wp_enqueue_style( 'custom-style', get_stylesheet_uri(),
        array( $parenthandle ),
        $theme->get('Version') // this only works if you have Version in the style header
    );
}

Once done, just save the file like in the previous step.

Note: For this method, we recommend reading the official Child Themes and Including Assets documentation to make sure your child theme’s stylesheets are loaded properly.

You’ve now created a very basic child theme. When you go to Appearance » Themes in your WordPress admin panel, you should see the Twenty Twenty-One Child option.

Click the ‘Activate’ button to start using the child theme on your site.

Activating a child theme in WordPress admin

Method 2: Creating a Child Classic Theme With a Plugin

This next method uses the Child Theme Configurator plugin. This easy-to-use WordPress plugin lets you create and customize WordPress child themes quickly without using code, but it only works well with a classic (non-block) theme.

The first thing you need to do is install and activate the WordPress plugin. On activation, you need to navigate to Tools » Child Themes in your WordPress dashboard.

In the Parent/Child tab, you’ll be asked to choose an action. Just select ‘CREATE a new Child Theme’ to get started.

Creating a new child theme with Child Theme Configurator

Then, select a parent theme from a dropdown menu. We will select the Hestia theme.

After that, just click the ‘Analyze’ button to make sure the theme is suitable for use as a parent theme.

Choosing a parent theme in Child Theme Configurator

Next, you will be asked to name the folder the child theme will be saved in. You can use any folder name you want.

Below that, you need to select where to save the new styles: in the primary stylesheet or a separate one.

The primary stylesheet is the default stylesheet that comes with your child theme. When you save new custom styles to this file, you are directly modifying the main styles of your child theme. Every modification will overwrite the original theme’s style.

The separate option allows you to save a new custom style to a separate stylesheet file. This is useful if you want to preserve the original theme’s style and not overwrite it.

For demonstration purposes, we will choose the first option. But as you get more creative with your child theme customizations, you can always repeat this process and select the second option.

Choosing where to save the stylesheet in Child Theme Configurator

Moving down, you have to choose how the parent theme’s stylesheet will be accessed.

We will just go with the default ‘Use the WordPress style queue’ as it will let the plugin determine the appropriate actions automatically.

Choosing the parent theme stylesheet handling in Child Theme Configurator

When you get to step 7, you’ll need to click the button labeled ‘Click to Edit Child Theme Attributes’.

You can then fill in the details of your child theme.

Filling out the child theme details in Child Theme Configurator

When you create a child theme manually, you will lose the parent theme’s menus and widgets. Child Theme Configurator can copy them from the parent theme to the child theme. Check the box in step 8 if you’d like to do this.

Finally, click the ‘Create New Child Theme’ button to make your new child theme.

Clicking the Create New Child Theme button in Child Theme Configurator

The plugin will create a folder for your child theme and add the style.css and functions.php files you’ll use to customize the theme later.

Before you activate the theme, you should click the link near the top of the screen to preview it and make sure it looks good and doesn’t break your site.

Previewing a child theme in Child Theme Configurator

If everything seems to be working, click the ‘Activate & Publish’ button.

Now, your child theme will go live.

At this stage, the child theme will look and behave exactly like the parent theme.

Activating a child theme after it was made with Child Theme Configurator

Method 3: Creating a Child Block Theme With a Plugin

If you use a block theme, then WordPress offers an easy way to create a child theme with the Create Block Theme plugin.

First, you will need to install and activate the WordPress plugin. After that, go to Appearance » Create Block Theme.

Here, simply select ‘Create child of [theme name].’ We are using Twenty Twenty-Four in this example.

Once you’ve selected that option, fill out your theme’s information.

Creating a child theme with Create Block Theme

Below that, you can do more things like uploading a screenshot for the theme to differentiate it from other themes, adding image credits, linking to must-have WordPress plugins, adding theme tags, and so on.

Once you are done configuring the settings, just scroll all the way down and hit the ‘Generate’ button.

Generating a child theme with Create Block Theme

The plugin will now create and download a new child theme zip file to your computer.

If you open it, you will see three files: readme, style.css, and theme.json.

The theme.json file defines various aspects of a block theme, including its colors, typography, layout, and more. The plugin creates this file by default so that you can override or extend the parent theme’s style in the child theme later on.

At this stage, all you need to do next is go to Appearance » Themes.

After that, click ‘Add New Theme.’

Adding a new theme in WordPress

Next, select ‘Upload Theme.’

Then, choose the zip file and click ‘Install Now’ to install the WordPress theme.

Uploading a child theme in WordPress

Bonus Tip: Find Out If Your Theme Has a Child Theme Generator

If you are lucky, then your WordPress theme may already have an existing feature to create a child theme.

For example, if you use Astra, then you can go to the Astra Child Theme Generator website. After that, just fill out your child theme name and click the ‘Generate’ button.

Astra Child Theme Generator website

Your browser will then automatically download your child theme to your computer, which you can then install on WordPress yourself.

We also found some other popular WordPress themes that have a child theme generator:

How to Customize Your Classic Child Theme

Note: This section is for classic WordPress theme users. If you use a block theme, then just skip to the next section.

Technically, you can customize your child theme without code by using the Theme Customizer. The changes you make there won’t affect your parent theme. If you are not comfortable with coding yet, then feel free to use the Customizer.

That said, we also recommend customizing the child theme with code.

Besides learning more about WordPress theme development, code customization allows for the changes to be documented within the child theme’s files, making it easier to track them.

Now, the most basic way to customize a child theme is by adding custom CSS to the style.css file. To do that, you need to know what code you need to customize.

You can simplify the process by copying and modifying the existing code from the parent theme. You can find that code by using the Chrome or Firefox Inspect tool or by copying it directly from the parent theme’s CSS file.

Method 1: Copying Code from the Chrome or Firefox Inspector

The easiest way to discover the CSS code you need to modify is by using the inspector tools that come with Google Chrome and Firefox. These tools allow you to look at the HTML and CSS behind any element of a web page.

You can read more about the inspector tool in our guide on the basics of inspect element: customizing WordPress for DIY users.

When you right-click on your web page and use the inspect element, you will see the HTML and CSS for the page.

As you move your mouse over different HTML lines, the inspector will highlight them in the top window. It will also show you the CSS rules related to the highlighted element, like so:

Demonstrating how the Chrome inspect tool works

You can try editing the CSS right there to see how it would look. For example, let’s try changing the background color of the theme’s body to #fdf8ef. Find the line of code that says body { and inside it, the code that says color: .

Just click the color picker icon next to color: and paste the HEX code into the appropriate field, like so:

Now, you know how to change the background color using CSS. To make the changes permanent, you can open your style.css file in the child theme directory (using the file manager or FTP).

Then, paste the following code below the child theme information, like so:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

body {
    background-color: #fdf8ef
}

Here is what it will look like if you go to the WordPress admin and open Appearance » Theme File Editor:

Adding custom CSS in a child theme's stylesheet in the theme file editor

If you are a beginner and want to make other changes, then we recommend getting familiar with HTML and CSS so that you know exactly what element each code is referring to. There are many HTML and CSS cheat sheets online that you can refer to.

Here is the complete stylesheet that we have created for the child theme. Feel free to experiment and modify it:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

.site-title {
color: #7d7b77;
}
.site-description {
color: #aba8a2;
}
body {
background-color: #fdf8ef;
color: #7d7b77;
}
.entry-footer {
color: #aba8a2;
}
.entry-title {
color: #aba8a2;
font-weight: bold;
}
.widget-area {
color: #7d7b77;
}

Method 2: Copying Code From the Parent Theme’s style.css File

Maybe there are a lot of things in your child theme that you want to customize. In that case, it may be quicker to copy some code directly from the parent theme’s style.css file, paste it into your child theme’s CSS file, and then modify it.

The tricky part is that a theme’s stylesheet file can look really long and overwhelming to beginners. However, once you understand the basics, it’s actually not that hard.

Let’s use a real example from the Twenty Twenty-One parent theme’s stylesheet. You need to navigate to /wp-content/themes/twentytwentyone in your WordPress installation folder and then open the style.css file in your file manager, FTP, or Theme File Editor.

You will see the following lines of code:

:root {
/* Colors */
--global--color-black: #000;
--global--color-dark-gray: #28303d;
--global--color-gray: #39414d;
--global--color-light-gray: #f0f0f0;
--global--color-green: #d1e4dd;
--global--color-blue: #d1dfe4;
--global--color-purple: #d1d1e4;
--global--color-red: #e4d1d1;
--global--color-orange: #e4dad1;
--global--color-yellow: #eeeadd;
--global--color-white: #fff;
--global--color-white-50: rgba(255, 255, 255, 0.5);
--global--color-white-90: rgba(255, 255, 255, 0.9);
--global--color-primary: var(--global--color-dark-gray); /* Body text color, site title, footer text color. */
--global--color-secondary: var(--global--color-gray); /* Headings */
--global--color-primary-hover: var(--global--color-primary);
--global--color-background: var(--global--color-green); /* Mint, default body background */
--global--color-border: var(--global--color-primary); /* Used for borders (separators) */
}

Lines 3 to 15 control the type of colors (like yellow, green, purple) that the entire theme will use in their specific HEX codes. And then, for lines like ‘global-color-primary’ or ‘global-color-secondary,’ that means those are the primary and secondary colors of that theme.

You can copy these lines of code to your child theme’s stylesheet and then change the HEX codes to create your perfect color scheme.

As you scroll down in the parent theme’s stylesheet, you will notice that other variables may have these color variables, too, like here:

/* Buttons */
--button--color-text: var(--global--color-background);

This basically means all button texts will use the same color as declared in --global--color-background:, which is mint green (--global--color-green: #d1e4dd). If you change the HEX in --global--color-green:, then the button text will look different, too.

Note: If you use the Twenty Twenty-One child theme and do not see any changes, then you may need to update the ‘Version’ part of the theme file information (for example, from 1.0 to 2.0) every time you update the style.css file.

You can also follow these tutorials to experiment with your child theme customizations:

How to Customize Your Block Child Theme

If you use a child block theme, then most of your customizations will be done to your theme.json file, not style.css.

However, during our testing, we found the process to be complicated. Unlike classic child themes, there’s a bigger knowledge gap you need to fill in (especially about JSON and how CSS is handled there) if you are new to WordPress theme development.

That said, we found a much easier alternative using the Create Block Theme plugin. This tool can record any changes made in the WordPress Full Site Editor in your child theme.json’s file. So, you won’t have to touch any code at all because the plugin will take care of it for you.

Let’s show you an example. First, open the WordPress Full Site Editor by going to Appearance » Editor.

Selecting the Full-Site Editor from the WordPress admin panel

You will see several menus to choose from.

Here, just select ‘Styles.’

Opening the Styles menu in Full Site Editor

On the next page, you will see several built-in style combinations to choose from.

For our purpose, you can simply skip all of that and just click the pencil icon.

Clicking the Edit Styles button in the Full Site Editor

Now, let’s try changing some parts of your child theme, like the fonts.

For this example, go ahead and click ‘Typography’ in the right sidebar.

Clicking the Typography menu in Full Site Editor

Next, you will see some options to change the theme’s global fonts for text, links, headings, captions, and buttons.

Let’s click ‘Headings‘ for the sake of demonstration.

Clicking Headings in the Full Site Editor

In the Font dropdown menu, change the original pick to any font that’s available.

Feel free to change the appearance, line height, letter spacing, and letter casing if needed.

Styling headings in the Full Site Editor

Once you are done, just click ‘Save.’ After that, you can click the Create Block Theme button (the wrench icon) next to ‘Save.’

Then, click ‘Save Changes.’ This will save all of your changes to the child theme.json file.

Saving a child block theme's changes using the Create Block Theme plugin

If you open your theme.json file, then you will see the changes reflected in the code.

Here’s what we saw after we updated our child theme:

A child block theme.json file after changes were made to it using the Create Block Theme plugin

As you can see, now the file includes code that indicates that heading tags will use the Inter font with semi-bold appearance, 1.2 line height, 1 pixel line spacing, and in lowercase.

So, whenever you edit your child block theme, make sure to click the wrench icon and save your changes so that they are well-documented.

How to Edit a Child Theme’s Template Files

Most WordPress themes have templates, which are theme files that control the design and layout of a specific area inside a theme. For example, the footer section is usually handled by the footer.php file, and the header is handled by the header.php file.

Each WordPress theme also has a different layout. For example, the Twenty Twenty-One theme has a header, content loop, footer widget area, and footer.

If you want to modify a template, then you have to find the file in the parent theme folder and copy it to the child theme folder. After that, you should open the file and make the modifications you want.

For example, if you use Bluehost and your parent theme is Twenty Twenty-One, then you can go to /wp-content/themes/twentytwentyone in your file manager. Then, right-click on a template file like footer.php and select ‘Copy.’

Copying footer.php in Bluehost file manager

After that, enter the file path of your child theme.

Once you are done, simply click ‘Copy Files.’

Entering the child theme's file path to copy and paste the footer.php into inside Bluehost file manager

You will then be redirected to the file path.

To edit the footer.php file, just right-click on it and select ‘Edit.’

Editing footer.php in Bluehost file manager

As an example, we will remove the ‘Proudly powered by WordPress’ link from the footer area and add a copyright notice there.

To do that, you should delete everything between the <div class= "powered-by"> tags:

<div class="powered-by">
				<?php
				printf(
					/* translators: %s: WordPress. */
					esc_html__( 'Proudly powered by %s.', 'twentytwentyone' ),
					'<a href="' . esc_url( __( 'https://wordpress.org/', 'twentytwentyone' ) ) . '">WordPress</a>'
				);
				?>
			</div><!-- .powered-by -->

Then you need to paste in the code you find below those tags in the example below:

<div class="powered-by">
<p>© Copyright <?php echo date("Y"); ?>. All rights reserved.</p>
</div><!-- .powered-by -->

Here’s what you should now have in the text editor:

Replacing the WordPress footer links in footer.php inside Bluehost file manager

Go ahead and save the file to make the changes official.

After that, visit your website to see the new copyright notice.

Adding a dynamic copyright notice in footer.php

How to Add New Functionality to Your Child Theme

The functions.php file in a theme uses PHP code to add features or change default features on a WordPress site. It acts like a plugin for your WordPress site that’s automatically activated with your current theme.

You’ll find many WordPress tutorials that ask you to copy and paste code snippets into functions.php. But if you add your modifications to the parent theme, then they will be overwritten whenever you install a new update to the theme.

That’s why we recommend using a child theme when adding custom code snippets. In this tutorial, we will add a new widget area to our theme.

We can do that by adding this code snippet to our child theme’s functions.php file. To make the process even safer, we recommend using the WPCode plugin so that you don’t edit the functions.php file directly, reducing the risk of errors.

You can read our guide on how to add custom code snippets for more information.

Here is the code you need to add your functions.php file:

// Register Sidebars
function custom_sidebars() {

$args = array(
'id'            => 'custom_sidebar',
'name'          => __( 'Custom Widget Area', 'text_domain' ),
'description'   => __( 'A custom widget area', 'text_domain' ),
'before_title'  => '<h3 class="widget-title">',
'after_title'   => '</h3>',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget'  => '</aside>',
);
register_sidebar( $args );

}
add_action( 'widgets_init', 'custom_sidebars' );

Once you save the file, you can visit the Appearance » Widgets page of your WordPress dashboard.

Here, you will see your new custom widget area that you can add widgets to.

Creating a custom widget area for a child theme

There are plenty of other features you can add to your theme using custom code snippets. Check out these extremely useful tricks for the WordPress functions.php file and useful WordPress code snippets for beginners.

How to Troubleshoot Your WordPress Child Theme

If you’ve never created a child theme before, then there’s a good chance you’ll make some mistakes, and that’s normal. This is why we recommend using a backup plugin and creating a local site or staging environment to prevent fatal errors.

All that being said, don’t give up too quickly. The WordPress community is very resourceful, so whatever problem you are having, a solution probably already exists.

For starters, you can check out our most common WordPress errors to find a solution.

The most common errors you’ll probably see are syntax errors caused by something you missed in the code. You’ll find help in solving these issues in our quick guide on how to find and fix the syntax error in WordPress.

Additionally, you can always start again if something goes very wrong. For example, if you accidentally deleted something that your parent theme required, then you can simply delete the file from your child theme and start over.

We hope this article helped you learn how to create a WordPress child theme. You may also want to check out our ultimate guide to boost WordPress speed and performance and our expert pick of the best drag-and-drop page builders to easily design your website.

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.

The post How to Create a WordPress Child Theme (Beginner’s Guide) first appeared on WPBeginner.

How to Limit Comment Length in WordPress (Easy Tutorial)

Do you want to limit comment length in WordPress?

WordPress comments encourage discussions around your blog post content. However, you may find that comments that are very brief or overly long are not very helpful.

In this article, we will show you how to easily limit comment length in WordPress.

Limit Comment Length in WordPress

Why Limit Comment Length in WordPress?

An active comment area is a great way to build a community around your WordPress blog. Visitors can give feedback, ask questions, and offer their own points of view on the topic.

However, not all comments are helpful.

We’ve been moderating WordPress comments for well over a decade. In our experience, we’ve found that the most helpful comments are above 60 characters and below 5000 characters in length.

One-word comments are usually not very helpful. In most cases, they are spam comments where the author just wants a backlink from your site.

On the other hand, long comments above 5,000 characters are often rants or complaints. Sometimes, they are not even relevant to the article.

Setting comment length limits in WordPress can improve the overall quality of your comments and discourage spam comments. However, there is no built-in way of doing this in WordPress.

That being said, let’s take a look at how to control comment length in WordPress by setting minimum and maximum limits.

How to Limit Comment Length in WordPress

You can limit comment length in WordPress by adding code to your functions.php file. However, keep in mind that the smallest error while entering the code can break your site and make it inaccessible.

That’s why we recommend always using WPCode to insert code snippets into your WordPress site. It is the best WordPress code snippets plugin on the market that makes it safe and easy to add custom code.

First, you need to install and activate the WPCode plugin. For detailed instructions, see our step-by-step guide on how to install a WordPress plugin.

Note: WPCode also has a free version that you can use for this tutorial. However, upgrading to the paid plan will give you access to more features like a larger code snippets library, conditional logic, and more.

Upon activation, visit the Code Snippets » + Add Snippet page from the WordPress admin sidebar.

Here, click the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can start by adding a title for your code snippet. This name won’t be displayed on the website front end and can be anything you like.

Next, choose the ‘PHP Snippet’ option as the Code Type from the dropdown menu in the right corner of the screen.

Choose the PHP Snippet option for comment length limit

Once you have done that, simply copy and paste the following code snippet into the ‘Code Preview’ box:

add_filter( 'preprocess_comment', 'wpb_preprocess_comment' );
 
function wpb_preprocess_comment($comment) {
    if ( strlen( $comment['comment_content'] ) > 5000 ) {
        wp_die('Comment is too long. Please keep your comment under 5000 characters.');
    }
if ( strlen( $comment['comment_content'] ) < 60 ) {
        wp_die('Comment is too short. Please use at least 60 characters.');
    }
    return $comment;
}

This code snippet works by adding a filter hook to preprocess_comment. This filter is run before WordPress saves any comments to the database or performs any pre-processing on submitted comments.

It checks the comment length and displays an error message if it is too short or too long. By default, the comment limit is set to a minimum of 60 characters and a maximum of 5,000 characters in this snippet.

However, to set your own comment limit, just replace the number 5,000 in the code with your maximum limit number.

Similarly, you can replace the number 60 in the code to set a different minimum comment limit on your WordPress website.

You can also change the message that will be displayed on your website when a user exceeds or falls short of the comment limit. Simply type the sentence you want to display after the wp_die lines in the code.

Edit comment limit snippet

After that, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

The custom code will be automatically executed on your website upon activation.

Choose an insertion method

If you only want to limit comment length on specific website pages, then you can also do that.

Simply scroll down to the ‘Conditional Logic’ section and toggle the ‘Enable Logic’ switch.

After that, choose the ‘Show’ option from the ‘Conditions’ dropdown menu and click the ‘+ Add new group’ button.

Enable the Conditional Logic toggle

This will open a new tab where you must select the ‘Page URL’ option from the dropdown menu on the left.

Next, type the URL of the page where you want to limit the comment length in the field on the right.

Now, the code snippet will only be activated on the page with the URL you have just entered.

Type the conditional logic

Scroll back to the top of the page and toggle the ‘Inactive’ switch to ‘Active’.

Finally, click the ‘Save Snippet’ button to store your settings.

Save the comment limit snippet

Now, when a user types a comment that falls short of your minimum comment length, this message will be displayed on their screens.

Users won’t be able to post a comment until it is at least the minimum length you chose.

An Error Message Is Displayed if a Comment is Too Short or Too Long

Similarly, when a user types a comment that exceeds your maximum limit, this message will be show on their screens.

This will help reduce rants and spam comments on your website.

Message preview for a long comment

Bonus: Improve Comment Engagement on Your WordPress Site

Controlling comment length is just one way to increase engagement in your WordPress comments section. This is great for keeping visitors on your site for longer and can even benefit your site’s SEO when users’ comments contain relevant keywords and add context to your content.

You can also easily further improve the comments section on your website using Thrive Comments.

The Thrive Comments WordPress plugin

It is the best WordPress comments plugin that comes with a dedicated moderation board, lets you lazy load comments, allows users to leave comments with their social media profiles, and more.

Plus, the tool enables you to add an upvote/downvote functionality to reduce spam and encourage interesting comments on your website.

Thrive Comments even lets you feature encouraging comments at the top and bury offensive or irrelevant comments at the bottom of the discussion section.

Feature comment from dropdown menu

This allows you to reward users who are adding the most value to the discussion while politely discouraging other users from leaving unhelpful comments.

For detailed instructions, you may want to see our tutorial on how to feature or bury comments in WordPress.

We hope this tutorial helped you learn how to limit comment length in WordPress. You may also want to learn how to increase your blog traffic or check out our list of the best WordPress plugins to grow your site.

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.

The post How to Limit Comment Length in WordPress (Easy Tutorial) first appeared on WPBeginner.

How to Add a Facebook Like Box / Fan Box in WordPress

Do you want to add a Facebook Like Box to your WordPress website?

Adding a Facebook Like Box to your website makes it easy for your audience to like and follow your Facebook page. The more likes you get, the more reputable and trustworthy your brand will look to new users.

In this article, we will show you how to add a Facebook Like Box in WordPress.

How to Add a Facebook Like Box or Fan Box in WordPress

Why Add a Facebook Like Box on Your WordPress Website?

Adding a Facebook Like Box to your WordPress website has some great perks.

First, it helps engage people by letting them easily like your Facebook fan page or business page. This means your posts will show up in their Facebook feed, so you can keep reaching people beyond your website.

Also, the Facebook page Like Box shows how many people have liked your Facebook page. This can work as social proof and encourage more visitors to click ‘Like.’

This tutorial will show you two ways to add a Facebook Like Box: one using a social plugin and the other with code. You can use the quick links below to navigate through our article:

Note: A Facebook Like Box is different from a Like Button. If you want to display that on your website instead, then you can check out our step-by-step guide on how to add a Facebook Like Button in WordPress.

This first method is the easiest and recommended way for beginners to add a Facebook Like Box to their sites. It will also allow you to display your Facebook feed on your website if you wish.

This method uses Smash Balloon, which is a user-friendly WordPress plugin that allows you to embed various social media feeds in WordPress, along with a Like Box.

For this tutorial, you can use the free Smash Balloon Social Post feed plugin. But if you want more features beyond the Like Box (like displaying videos, photos, and events), then we recommend upgrading to the Pro version.

Set Up the Smash Balloon Facebook Feed Plugin

First, you need to install the WordPress plugin in the admin area. After that, go to Facebook Feed » All Feeds and click ‘Add New.’

Creating a new Facebook Feed in the free Smash Balloon plugin

Now, select the ‘Timeline’ feed type.

Then, simply click the ‘Next’ button.

Selecting the Timeline Facebook Feed type in Smash Balloon

At this stage, you will need to connect your Facebook page to your WordPress website.

What you need to do is click the ‘Add New’ button.

Adding a new Facebook Feed source in Smash Balloon

Smash Balloon will direct you to a new screen.

Here, just select ‘Page’ for the source type and then click ‘Connect to Facebook.’

Connecting Smash Balloon with Facebook

Now, you need to log in to your Facebook account.

After that, choose which page(s) for which you want to display the Like Box on your WordPress blog or website. Then, click ‘Next.’

Selecting Facebook Pages to use as sources in Smash Balloon

You will now see the Smash Balloon’s permission settings. We recommend enabling them all to make sure everything works well.

Now, go ahead and click ‘Done.’

The Smash Balloon permission settings when connected to Facebook

The last popup will simply confirm that you’ve successfully linked Smash Balloon with Facebook.

Simply click ‘OK’ to continue.

Confirming that the Smash Balloon and Facebook connection is successful

Smash Balloon will now redirect you to the admin area, where you have to select a Facebook page to use in your timeline feed.

Just pick a page and click ‘Add.’

Choosing a Facebook page to use as a source in Smash Balloon

You will now see the Facebook page you’ve just connected to as a source in the Smash Balloon plugin page.

Simply pick that and click ‘Next.’

Selecting a Facebook page to use as a source for the Smash Balloon Facebook Feed in WordPress

Customize the Facebook Like Box

At this stage, Smash Balloon will bring you to the Facebook feed editor.

The first step is to click ‘Feed Layout’ above the Color Scheme option.

Selecting the Feed Layout menu in the Smash Balloon Facebook Feed editor

Simply scroll down to the ‘Number of Posts’ section.

After that, set the number for both Desktop and Mobile to 0. This will remove the display of all your recent posts and have the feed display the Like Box only.

Alternatively, if you also want to show your Facebook feed along with the Like Box, then you can follow our tutorial on how to create a custom Facebook feed in WordPress.

Removing all display of Facebook post in the Smash Balloon Facebook Feed

Now, go back up.

Then, click ‘Customize’ to go back to the feed editor page.

Clicking the Customize button in Smash Balloon to return to the main Facebook Feed editor

At this stage, you can remove the header of your Facebook feed.

What you need to do is move down to the ‘Sections’ part and select ‘Header.’

Opening the Header section setting in Smash Balloon

This Header setting determines what your Facebook feed’s header will look like.

But in this case, you need to hide it, so just turn off the ‘Enable’ toggle.

Disabling the Facebook Feed header in Smash Balloon

Let’s now go back to the main feed editor page and open the ‘Like Box’ setting. After that, simply turn on the ‘Like Box’ feature.

On this page, you can also adjust the Like Box’s size, position, cover photo display, custom width, custom call-to-action text, and so on.

Enabling the Facebook Like Box feature in Smash Balloon

Once that’s done, just hit the ‘Save’ button in the top right corner.

Embed the Facebook Like Box on Your WordPress Page or Post

At this stage, you can display the Facebook Like Box on a page or a widget-ready area like a sidebar.

To do this, click ‘Embed’ at the top right corner. Now, the Embed Feed popup will appear, giving you two options to display the Like Box.

One is to use a shortcode, and the other is to directly add it to a page or a widget-ready area. The second option is much easier, so we will show you that method first.

The Embed Feed popup for Facebook Feed in Smash Balloon

If you want to add the Like Box to a specific page, click the ‘Add to a Page’ button.

Now, just select a page to add the feature to and click ‘Add.’

Selecting a page to insert the Facebook Feed to in Smash Balloon

You will now arrive at the Gutenberg block editor.

Go ahead and click the ‘+ Add a Block’ button, as instructed by Smash Balloon.

Clicking the Add Block button as instructed by Smash Balloon in the block editor

Once the block inserter library is open, you need to find the Facebook Feed block.

Then, simply drag and drop it wherever it looks best on the page.

Finding Smash Balloon's Facebook Feed block in the block editor

In the block, select the Facebook feed with the Like Box you just created earlier.

The block will then display the Like Box.

Choosing a Smash Balloon Facebook Feed to embed in the block editor

But what if you have multiple Facebook pages and have set up a Like Box for each one using Smash Balloon?

You can also switch between them in the block settings sidebar by picking a feed from the ‘Select a Feed’ dropdown menu.

Switching to a different Facebook Feed in the Smash Balloon block settings sidebar inside the block editor

All you need to do now is click the ‘Update’ button to make the changes official.

Here’s what our Like Box looks like on our demo site:

An example of the Facebook Like Box created with Smash Balloon

If you use a block WordPress theme, then you can also use the Full Site Editor to add the Facebook Like Box block to your theme’s page templates.

For more information about the Full Site Editor, just read our beginner’s guide to Full Site Editing.

Embed the Facebook Like Box Widget in WordPress

If you use a classic WordPress theme, then you may want to display the Facebook Like Box in a widget-ready area, like a sidebar, header, or footer. It’s a great way to show the Like Box without distracting users from the main content on the page.

In the Embed Feed popup, select ‘Add to a Widget’ to go to the block-based widget editor.

Now, like in the previous method, just click the ‘+ Add Block’ button, find the Facebook Feed block, and drag it onto your desired area.

On our demo site, we want to use the Like Box as a WordPress sidebar widget.

Finding the Smash Balloon Facebook Feed widget in the widget editor

In the block, select the Facebook Feed with the Like Box you created earlier.

Then, click ‘Update’ to make the changes live.

Selecting a Smash Balloon Facebook Feed to embed in the widget editor

And you are done!

Here’s what the sidebar on our test site looks like with the Like Box widget:

An example of what the Facebook Like Box widget looks like in the sidebar

Embed the Facebook Like Box Widget With a Shortcode

If the two previous methods don’t work, then we recommend adding the Facebook Like Box or Fan Box using a shortcode.

Simply copy the shortcode from the Embed Feed popup earlier and add it anywhere on your website.

Copying the Facebook Feed embed shortcode in Smash Balloon

For more information on using shortcodes, you can read our guide on how to add shortcodes in WordPress.

Method 2: Adding a Facebook Like Box With Code

If you are only interested in displaying a Like Box without adding any other types of Facebook feeds, then using a Facebook page plugin may seem like overkill. In this case, you can add the Like Box using code instead.

This method may seem intimidating for beginners, but we will show you a foolproof way to insert code using WPCode. It’s a WordPress plugin that makes it easy to add custom code snippets to WordPress without breaking your site.

For this guide, the free WPCode version is enough, although you can upgrade to the Pro version for advanced features like testing mode and a cloud-based code snippets library.

First, let’s install the plugin in WordPress. Once it’s active, go to Code Snippets » + Add Snippet. Then, select ‘Add Your Custom Code (New Snippet)’ and click ‘Use snippet.’

Adding custom code in WPCode

You will now arrive at the code editor. Let’s give your custom code snippet a name first so that you can easily identify it later. For this one, we will name it ‘Facebook JavaScript SDK’ because that’s what we will add here.

Now, keep this tab open and create a new tab on your browser to go to the Facebook Developers page.

In the menu, click ‘Log In’ to sign in to your Facebook account.

Logging into the Facebook Developers page

If this is your first time accessing the page, then complete the onboarding wizard to create a free account.

You will then be directed to the Facebook Developers dashboard. Let’s click on the ‘Create App’ button.

How to create a new Facebook app

On the next page, just select ‘Other’ for the use case.

After that, click on the ‘Next’ button.

Choosing a Facebook use case

Now, you will see all the different apps that you can create for your Facebook page.

To create a Like Box, you can just select ‘Business’ and then click on ‘Next.’

Creating a business application in Facebook

Let’s now give your app a name. It can be anything you like since this is just for reference. You can also enter your email address and select an optional Business Account.

Finally, just click ‘Create app.’

Creating a Facebook application in the Developers console

Let’s now go to the Facebook Developers page for social plugins.

Then, scroll down until you find a section like in the screenshot below:

Here, make sure to fill out your Facebook page URL, empty the ‘Tabs’ field, and specify the width and height of the Like Box if needed.

You can also choose to use a smaller header, disable the cover photo, and more. We’ve also chosen to adapt the Like Box to fit the container width so that the size will adjust responsively to where it’s placed on the website.

Once done, click the ‘Get Code’ button. You will then see a popup that shows you two types of code snippets: JavaScript SDK and iFrame. Both will display your Like Box, but in general, JavaScript SDK is a much better option.

The JavaScript SDK codes to embed the Facebook Like Box

JavaScript SDKs are usually faster because they are directly embedded into the webpage, allowing them to load as part of the main document. iFrames require loading an entire HTML document, which can slow down the page load time.

In the JavaScript SDK tab, make sure the app name you created earlier has been selected.

Then, go ahead and copy the JavaScript SDK API code from Step 2. Now, keep this tab open, but switch to the WPCode tab and paste the code there.

You can leave the Code Type as ‘HTML Snippet.’

Pasting the Facebook JavaScript API to WPCode

Now, scroll down to the ‘Insertion’ section.

The Insert Method can be left as ‘Auto Insert,’ while the Location should be changed to ‘Site Wide Body.’

Finally, just make the code active and click ‘Save Snippet.’

Choosing Auto Insert and Site Wide Body for the code's Insertion settings in WPCode

Next, you will create a second code snippet. You can follow the same steps as before and call it something like ‘Facebook Like Box.’

After that, switch to the Facebook Developers page for social plugins from earlier and copy the code from Step 3.

Navigate to the WPCode tab again and paste the Step 3 code in the Code Preview box. The Code Type can be ‘HTML Snippet.’

Pasting the Facebook Like Box custom code snippet in WPCode

Let’s scroll down to the ‘Insertion’ section.

If you use ‘Auto Insert,’ then you can make the Like Box appear automatically in multiple places that fit the Location category.

In our example, we have decided to choose the ‘Site Wide Footer’ location, which means the Like Box will appear in the footer.

There are other options, too, like Insert Before Post, to display the Like Box before all of your WordPress blog posts.

Selecting the Side Wide Footer location in WPCode

On the other hand, the ‘Shortcode’ method allows you to create a custom shortcode.

You can then add it to specific parts of your website using the shortcode block.

Creating a custom shortcode using WPCode

Once you’ve configured the Insertion settings, just make the code active and click ‘Save Snippet.’

That’s it! You can then visit your website to see what Like Box looks like:

An example of the Facebook Like Box added with WPCode

For more guides on displaying social feeds on your WordPress site, check out our article on adding social media feeds in WordPress.

We hope this article has helped you learn how to add a Facebook Like Box or Fan Box in WordPress. You may also want to check out our ultimate social media cheat sheet and list of the best social media plugins for WordPress.

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.

The post How to Add a Facebook Like Box / Fan Box in WordPress first appeared on WPBeginner.

How to List Future Upcoming Scheduled Posts in WordPress

Do you want to list your upcoming scheduled posts in WordPress?

Showing a list of future scheduled posts to your users can generate a buzz around your content and encourage visitors to return to your website. This can help you improve user interaction and engagement on your blog posts.

In this article, we will show you how to easily display future upcoming posts in WordPress, step by step.

List Future Upcoming Scheduled Posts in WordPress

Why Display Future Upcoming Posts in WordPress?

If you have been running a WordPress blog for a while, then you will know that publishing posts at a certain time can get more people to read them.

However, you can’t just sit around and wait for the right time to hit the publish button. That’s why WordPress has a built-in scheduling feature that lets you schedule posts to be published later.

This can help you focus on creating content and managing your editorial calendar like a pro.

Once you have scheduled the posts on your site, it is also a good idea to show a list of these upcoming articles to create hype around them and increase engagement on your blog.

Displaying future scheduled posts can be especially effective for content like serialized stories, product launches, or event announcements.

It may encourage users to discuss upcoming topics in the comments section, sign up for your newsletter, or even pre-register for events.

Having said that, let’s see how to easily list upcoming scheduled posts in WordPress.

You can easily show a list of scheduled upcoming posts on your WordPress site by adding custom code to your theme’s functions.php file. However, making even the smallest error while typing the code can break your site and make it inaccessible.

That is why we recommend always adding custom code using WPCode. It is the best WordPress code snippets plugin on the market that makes it safe and easy to add code to your website.

First, you need to install and activate the WPCode plugin. For detailed instructions, you can see our beginner’s guide on how to install a WordPress plugin.

Note: WPCode has a free plan that you can use for this tutorial. However, upgrading to the pro plan will give you access to more features like a cloud library for code snippets, a CSS snippet option, advanced conditional logic, and more.

Upon activation, visit the Code Snippets » + Add Snippet page from the WordPress dashboard and click the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can start by adding a name for your code snippet. The name is only for your identification and can be anything you like.

After that, choose ‘PHP Snippet’ as the Code Type from the dropdown menu on the right.

Choose PHP Snippet option for the code snippet to show a list of scheduled upcoming posts

Next, you need to copy and paste the following custom code into the ‘Code Preview’ box:

function wpb_upcoming_posts() { 
    // The query to fetch future posts
    $the_query = new WP_Query(array( 
        'post_status' => 'future',
        'posts_per_page' => 3,
        'orderby' => 'date',
        'order' => 'ASC'
    ));
 
// The loop to display posts
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $output .= '<li>' . get_the_title() .' ('.  get_the_time('d-M-Y') . ')</li>';
    }
    echo '</ul>';
 
} else {
    // Show this when no future posts are found
    $output .= '<p>No posts planned yet.</p>';
}
 
// Reset post data
wp_reset_postdata();
 
// Return output
 
return $output; 
} 
// Add shortcode
add_shortcode('upcoming_posts', 'wpb_upcoming_posts'); 
// Enable shortcode execution inside text widgets
add_filter('widget_text', 'do_shortcode');

After that, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

Keep in mind that you will still have to add a shortcode to show a list of upcoming posts on your WordPress website.

Choose an insertion method

Finally, scroll back to the top of the page to toggle the ‘Inactive’ switch to ‘Active’.

Once you do that, simply click the ‘Save Snippet’ button to store your settings.

Save the code snippet for showing scheduled posts

Display a List of Scheduled Upcoming Posts in the Sidebar of a Classic Theme

To display a list of upcoming posts in the WordPress sidebar, visit the Appearance » Widgets page from the WordPress dashboard. Keep in mind that this option will only be available if you are using a classic (non-block) theme.

Here, you need to click the add block ‘+’ button in the top left corner of the screen to open the block menu.

From here, drag and drop the Shortcode block into the sidebar section. After that, add the following shortcode into the block:

[upcoming_posts]

Add the shortcode for displaying a list of upcoming scheduled posts in the widget area

Next, click the ‘Update’ button at the top to store your settings.

Now, you can visit your WordPress site to view the list of upcoming scheduled posts in action.

A preview of list of upcoming scheduled posts

Display a List of Scheduled Upcoming Posts in the Full Site Editor

If you are using a block-based theme, then the Widgets menu tab won’t be available for you. In that case, you need to visit the Appearance » Editor page from the WordPress dashboard.

Once the editor opens up, click on ‘Pages’ and then simply choose a page where you want to add the shortcode from the options on the left.

Choose a page in the full site editor where you want to add a shortcode

The page of your choice will now be launched in the full site editor. Here, you must click the add block ‘+’ button to open the block menu and add the Shortcode block to the page.

After that, just add the following shortcode into the block:

[upcoming_posts]

Add shortcode to display scheduled upcoming posts in the FSE

Finally, click the ‘Save’ button at the top to store your settings.

Now, simply visit your WordPress site to view the list of scheduled upcoming posts.

Upcoming posts preview in FSE

Bonus: How to Display Recent Posts in WordPress

Apart from displaying upcoming posts, you may also want to show a list of recently published posts on your WordPress site.

Doing this can help introduce visitors to new content and encourage them to explore your website more.

You can easily display a list of recent posts in WordPress using the Latest Posts block in the Gutenberg editor.

Show post content in recent posts

After that, you can further customize this block by adding post excerpts, author name, publication date, or featured image.

For more information, you can see our tutorial on how to display recent posts in WordPress.

We hope this article helped you learn how to list future upcoming scheduled posts in WordPress. You may also be interested in our tutorial on how to bulk schedule posts in WordPress and our top picks for the best WordPress popular posts plugins.

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.

The post How to List Future Upcoming Scheduled Posts in WordPress first appeared on WPBeginner.

How to Highlight New Posts for Returning Visitors in WordPress

Are you wondering how to highlight new posts for returning visitors in WordPress?

Showing off the posts that were newly published on your website is one way to keep your readers updated and make sure they don’t miss out on your latest content.

In this step-by-step guide, we will show you how to highlight new posts for returning visitors in WordPress.

How to Highlight New Posts for Returning Visitors in WordPress

Why Highlight New Posts on Your WordPress Site?

Highlighting new posts on your WordPress site helps returning visitors easily discover your new content. This way, they won’t miss out on any fresh information or updates you’ve added to your blog.

Labeling new posts improves the user experience on your WordPress website. When a returning visitor reaches your website, they can easily spot which posts they haven’t read yet, saving them a lot of time and increasing your pageviews.

A good user experience on your site not only keeps visitors happy but also helps with SEO. When your site is easy to use, it improves your search engine rankings and increases the likelihood of visitors finding your content.

With that in mind, let’s see how you can highlight new posts for returning visitors in WordPress.

We will show you two methods: one with a WordPress plugin and the other with code. You can jump to a specific method using the quick links below:

Method 1: Highlight New WordPress Posts With a WordPress Plugin

This first method uses the Mark New Posts plugin. We recommend it for complete beginners because it’s very simple. This plugin will add a label to show which blog posts your site visitors haven’t seen yet.

Firstly, you need to install and activate the Mark New Posts plugin. If you need guidance, see our step-by-step guide on how to install a WordPress plugin.

After that, go to Settings » Mark New Posts from the WordPress admin area. You will now see the plugin’s settings page.

What you want to do now is select where to display the ‘New’ label. You can select After post title, Before post title, or Before and after post title.

We find that adding the label after the post title will look like a notification and grab users’ attention the most, so that’s what we’ve chosen.

Selecting the new post marker placement in Mark New Posts plugin

Next, you need to choose what the marker looks like in the Marker type setting. The options include “New” text, “New” text legacy, Orange circle, Flag, Picture, or None.

Be sure to explore each option to see which one looks best with your website design.

Selecting a new post marker type in Mark New Posts plugin

Another setting you can configure is the background color for the new post’s title. If you enable this, then when a reader visits a new post, they will see that the post title section has a background color. We didn’t find this setting necessary, so we disabled it.

In the ‘Consider a post as read’ setting, you can choose when to turn off the new post label: after it was opened, after it was displayed in the list, or after any web page of the blog was opened.

We suggest going with ‘after it was opened.’ This means that if a visitor hasn’t read several posts and opens one, then the new post label for the other articles won’t disappear.

Next, you can select how many days the post should stay highlighted as new, show all existing posts as new to new visitors, and disable the new label for custom post types.

The Mark New Posts plugin settings page

The last two settings are pretty advanced.

One is to ‘Allow outside the post list,’ which means you can highlight posts outside of the loop, like in widget-ready sidebar areas. Be cautious about enabling this setting, as it may create unwanted WordPress errors.

The other is ‘Use JavaScript for showing markers’, which is only recommended if the plugin is not compatible with the theme or other plugins being used on your blog. In most cases, you will want to keep this setting disabled.

Once you are done configuring the plugin settings, just click ‘Save.’

Clicking the Save button in Mark New Posts plugin

And that’s it! Go ahead and visit your website in incognito mode to see if the new labels for recent posts are live.

Here’s what it looks like on our demo website:

Example of the new post marker made by Mark New Posts plugin

Method 2: Highlight New Posts by Adding Custom Code

Are you unhappy with the new post label options given by the previous plugin? If so, then you can highlight new posts using custom code instead.

For beginners, this method may seem intimidating. But don’t worry because we will use the WPCode plugin to safely insert code snippets in WordPress without breaking your website.

WPCode also makes it easy to manage multiple custom code snippets, which will be handy in our case since we will be using more than one.

WPCode - Best WordPress Code Snippets Plugin

Note: While there is a free version of WPCode, we will use WPCode Pro because it allows you to insert the code snippets into the proper locations for this tutorial.

The first thing you need to do is install WPCode in WordPress. For setup instructions, go ahead and check out our article on how to install a WordPress plugin.

Next, go to Code Snippets » + Add Snippet from your WordPress dashboard. After that, select ‘Add Your Custom Code (New Snippet)’ and click the ‘Use snippet’ button.

Adding custom code in WPCode

Now, let’s add a title to your code snippet so that it’s easier to find it later on if needed. For this, you can name it something like ‘WordPress Last Visit Title Modifier.’

Then, select ‘PHP Snippet’ in the Code Type dropdown.

Giving the custom code snippet a title and selecting the PHP code type in WPCode

After that, you can copy and paste the code snippet below:

// Define a function to modify post titles based on the last visit
function wpb_lastvisit_the_title($title, $id) {

    // Check if not in the loop, a singular page, or a page post type; if true, return the original title
    if (!in_the_loop() || is_singular() || get_post_type($id) == 'page') return $title;

    // Check if no 'lastvisit' cookie is set or if it is empty; if true, set the cookie with the current timestamp
    if (!isset($_COOKIE['lastvisit']) || $_COOKIE['lastvisit'] == '') {
        $current = current_time('timestamp', 1);
        setcookie('lastvisit', $current, time() + 60 * 60 * 24 * 7, COOKIEPATH, COOKIE_DOMAIN);
    }

    // Retrieve the 'lastvisit' cookie value
    $lastvisit = $_COOKIE['lastvisit'];

    // Get the publish date of the post (in Unix timestamp format)
    $publish_date = get_post_time('U', true, $id);

    // If the post was published after the last visit, append a new span to the title
    if ($publish_date > $lastvisit) $title .= '<span class="new-article">New</span>';

    // Return the modified or original title
    return $title;
}

// Add a filter to apply the 'wpb_lastvisit_the_title' function to 'the_title' hook with priority 10 and 2 parameters
add_filter('the_title', 'wpb_lastvisit_the_title', 10, 2);

What this snippet does is modify WordPress post titles based on a user’s last visit.

It checks if the page is a blog post or not, and if not, then it will display the original title as is. But if it is a blog post, then the title will be modified.

Then, the snippet ensures the lastvisit cookie exists. If it doesn’t, then the code creates it and sets it to the current time. The function then compares this lastvisit time with the post’s publish date and adds a ‘New’ label to the title if the post is newer than the last visit.

Once you have inserted the code snippet, just scroll down and select ‘Auto Insert’ for the Insert Method.

Other than that, make sure to choose ‘Frontend only’ for the Location. This means the code will only run on the part of your WordPress blog that visitors interact with and not in your admin panel or other places.

Modifying the insertion settings in WPCode and activating and publishing the code

With that done, you can make the code ‘Active’ and click ‘Save Snippet.’

Now, repeat the step to add a new custom code snippet. This time, the code will style the ‘New’ label that is added to recent post titles based on the last visit of a user.

So, you can name it something like ‘Post Title New Label Style’ and the Code Type should be ‘CSS Snippet.’

Creating a CSS code to customize the new post label in WPCode

You can then copy and paste the following lines of code into the Code Preview box:

/* CSS to style the "New" label in blog post titles */
.new-article {
    background-color: #4CAF50; /* Green background color */
    color: #ffffff; /* White text color */
    padding: 2px 5px; /* Padding around the label */
    margin-left: 5px; /* Adjust the margin to your preference */
    border-radius: 3px; /* Rounded corners for the label */
    font-size: 12px; /* Adjust the font size to your preference */
}

This code snippet essentially customizes the ‘New’ post label using a custom background color, text color, padding, margin, border radius, and font size.

Feel free to adjust these elements to your preferences as you go along. Just make sure to use hex color codes or RGB values for the background and text colors.

In the Insertion section, select ‘Site Wide Header’ as the Location. After that, make the code ‘Active’ and click ‘Save Snippet.’

Choosing Site Wide Header as the code location in WPCode

And that’s it! To see if the code works, you can publish a new blog post and visit your website in incognito mode.

If the code is successful, then you should see a ‘New’ label next to your recent post titles.

Example of the new post label made with WPCode

Besides highlighting new posts for your returning visitors, there are many other ways to keep your readers engaged.

Ideally, you want visitors to check out not just one but three or more blog posts in one sitting. This shows that they are enjoying your content and are taking part in the community you are building.

However, sometimes, it can be hard for readers to find content that’s relevant to their interests. That’s where internal linking comes in.

Internal links are links that direct users to other pages or posts on your website.

You can use them directly within your blog posts. Or you can create a section under the post to show which blog posts are currently popular among your readers.

If you are not sure which internal links to use in a blog post, then All in One SEO (AIOSEO) has a link assistant feature that can give you some ideas.

View links details

For more information about internal linking, see our ultimate internal linking guide for SEO.

We hope this article has helped you learn how to highlight new posts for returning visitors in WordPress. You may also want to check out our WordPress SEO checklist for beginners and easy ways to increase your blog traffic.

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.

The post How to Highlight New Posts for Returning Visitors in WordPress first appeared on WPBeginner.

How to Stop Storing IP Address in WordPress Comments

Do you want to stop storing IP addresses in your WordPress comments?

By default, WordPress logs and stores the IP addresses of commenters to protect you against spammers. That said, with the rise of data privacy laws, you may want to stop this functionality to protect your website visitor data.

In this article, we will show you how to stop storing IP addresses in WordPress comments.

How to Stop Storing IP Address in WordPress Comments

Should You Stop Storing IP Addresses in WordPress Comments?

Unless your commenters use a VPN, WordPress will store their IP addresses on your website.

This is mainly used to combat spam comments from suspicious IP addresses. Some security plugins may also use IP addresses to put users in a comment blacklist or block malicious IP addresses to prevent threats like brute force attacks and DDoS attacks.

That said, some users may feel uncomfortable knowing that their IP address is logged after they leave a comment. They may think that this information can be used against them, which can make them hesitant to engage with your WordPress website.

If your website caters to a global audience, then storing IP addresses without user consent can also make your site less compliant with the General Data Protection Regulation (GDPR). This is because the GDPR classifies IP addresses as personal data.

Most WordPress web hosting providers keep raw access logs of all visitors to your website for a limited period of time. Plus, you can view these IP addresses when viewing the Comments page in the WordPress dashboard.

Now, let’s look at how to stop storing IP addresses and improve your WordPress security. Here is an overview of what we will cover:

This first method uses the WPCode plugin. We will use this plugin to insert a custom code snippet that stops your website from storing IP addresses from the comments section.

If this is your first time using code, don’t worry. WPCode’s user-friendly interface makes it easy to insert and manage custom code, even for a beginner.

To use WPCode, you need to install the plugin first. For more guidance, check out our article on how to install a WordPress plugin.

Note: This article will use the WPCode free version, but feel free to upgrade to a Pro plan for more advanced features like conditional logic and scheduled snippets.

Now, you need to go to Code Snippets » + Add Snippet from your WordPress admin panel. After that, click the ‘Use snippet’ button under ‘Add Your Custom Code Snippet’.

Adding custom CSS in WPCode

You will now see the Create Custom Snippet screen.

First things first, you have to add a title for your code snippet. It can be something like ‘Disable IP Address in Comments.’

In the Code Type dropdown, choose ‘PHP Snippet.’ Then, in the Code Preview box, you can insert the following code:

function wpb_remove_commentsip( $comment_author_ip ) { return ''; } add_filter( 'pre_comment_user_ip', 'wpb_remove_commentsip' );

After that, make sure the toggle in the top right corner says ‘Active’ and click ‘Save Snippet.’

It should look like this.

Removing IP addresses in the comments using WPCode

Now, the next time someone leaves a comment, you won’t see their IP address on the WordPress Comments page.

However, you will notice that previous comments still have this information stored. We will talk more about how to remove this data in the next part of the tutorial.

What the comment looks like after removing the IP address using WPCode

How to Remove IP Addresses From Older WordPress Comments

To remove IP addresses from your older WordPress comments, you will need to use phpMyAdmin. It’s a database management platform that usually comes with your WordPress hosting control panel.

Note: Before you do anything, we strongly recommend you back up your WordPress database first. That way, you can restore the database if you make a critical error.

Once you do that, you need to log in to your WordPress hosting account and look for the phpMyAdmin menu.

For Bluehost users, you will find phpMyAdmin by going to ‘Websites’ and selecting the website you want to configure in your dashboard. It should be under ‘Quick Links’.

Navigating to the phpMyAdmin in Bluehost

Inside phpMyAdmin, you can navigate to the ‘SQL’ tab.

After that, enter this query below:

UPDATE wp_comments SET comment_author_IP = '';

Note that if you have a custom WordPress database prefix, then please change wp_comments to your custom table prefix.

Once that’s done, simply click the ‘Go’ button below the text area to run your query.

Removing IP addresses in older WordPress comments using phpMyAdmin

At this stage, just go back to your WordPress Comments page to see if the query worked properly. That’s it!

We hope this article has helped you learn how to stop storing IP addresses in WordPress comments. You may also want to see our expert picks for the best WordPress security plugins and our guide to the tell-tale signs hackers have hijacked your WordPress site.

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.

The post How to Stop Storing IP Address in WordPress Comments first appeared on WPBeginner.

How to Add Google Search in a WordPress Site (The Easy Way)

Do you want to use Google search on your WordPress site?

By default, WordPress comes with a built-in search feature, but it is not very good. By adding Google Search in its place, you can display more accurate and relevant search results to visitors.

In this article, we will show you how to easily add Google Search to a WordPress site.

Add Google Search in a WordPress Site

Why Should You Use Google Search in WordPress?

The default WordPress search feature is not very useful and often fails to find relevant results to user queries. This forces many site owners to look for alternatives.

You can use a popular WordPress search plugin. However, the problem is that you still have to manage that plugin, and it will have an impact on your server resources.

On the other hand, you can use Google’s reliable and powerful search feature instead. It is free, allows you to limit the search to your sites only, and can be run from your WordPress site.

Plus, the Google search is fast, users already trust the brand, and you will not have to maintain or update it. You can even allow users to search external websites on Google if needed.

Having said that, let’s see how you can easily add a Google site search to your WordPress site.

How to Add Google Search to a WordPress Site

You can easily add Google Search to your WordPress site by visiting the Google Programmable Search Engine website.

From here, click the ‘Get Started’ button.

Click the get started button on the Programmable Search Engine page

This will direct you to the ‘Create a new search engine’ page, where you must add a name for the search form you are about to create.

Next, select the ‘Search specific sites or pages’ option in the ‘What to search?’ section and add your WordPress site’s URL.

Now, the Googe Site Search will only index the content available on your website. However, if you want Google to show search results from other websites as well, then you can choose the ‘Search the entire web’ option.

Add website URL to create Google Site search

Next, scroll down and toggle on the ‘Image Search’ option to allow your Google Search form to index images on your website. We recommend this option if you sell photos online, have a photography website, or run a travel blog.

After that, you can also toggle on the ‘Safe Search’ switch so that users won’t be shown inappropriate results for their queries.

Once you are done, click the ‘Create’ button.

Click create to generate a google search engine ID

Google will now generate your search engine ID code for you.

From here, simply copy the code and paste it into a notepad app or plain text editor.

Copy the Google Search Engine ID from the website

Now, you must visit your WordPress dashboard and edit your theme files to add the search to your site’s <body>. However, this can be risky, and the smallest error can break your website.

That is why we recommend using WPCode instead. It is the best WordPress code snippets plugin on the market that makes it safe and easy to add custom code.

First, you need to install and activate the WPCode plugin. For detailed instructions, see our beginner’s guide on how to install a WordPress plugin.

Note: WPCode has a free plan that you can use for this tutorial. However, upgrading to the pro version will give you access to more features like smart conditional logic, a cloud library of code snippets, and more.

Upon activation, visit the Code Snippets » + Add Snippet page from the WordPress admin sidebar. Here, click the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can type any name you like for the snippet. Then, select ‘Universal Snippet’ as the code type from the dropdown menu on the right.

Once you do that, simply paste the Google Search Engine ID into the ‘Code Preview’ box.

Paste the Google Search Engine ID into WPCode preview box

Then, scroll down to the ‘Insertion’ section and select the ‘Auto Insert’ mode. The Google Search form will be automatically added to your site upon activation.

After that, you can expand the ‘Location’ dropdown menu to choose where you want to display your search box.

For example, if you want to display the search form at the top of all your pages and posts, then you can select the ‘Insert Before Post’ option.

Choose location and insertion for the search engine ID

Next, scroll back to the top and toggle the ‘Inactive’ switch to ‘Active’.

Finally, click the ‘Save Snippet’ button to store your settings.

Save Google Search Engine ID snippet

You have successfully added a Google Site search form manually.

You can now visit your WordPress blog to see it in action.

Google Search preview

Alternative: Use SearchWP to Create an Amazing Search Form

If you find it difficult to add Google Site Search to your website or you are looking for an alternative, then you can use SearchWP for internal search.

It is the best WordPress search plugin on the market that automatically replaces the default search form and allows users to find anything they need on your site.

The SearchWP homepage

SearchWP is used by over 30,000 websites and lets you create a custom relevance scale to adjust the search algorithm.

You can also make any part of your site searchable including PDFs, custom post types, media, comments, custom fields, WooCommerce products, and more.

If you have a multilingual site, then you can also create a multilingual search with the plugin.

Configure SearchWP engine settings

However, you must keep in mind that, unlike Google Search, the plugin can only index and show results for content available on your website.

For more details, you can see our tutorial on how to improve WordPress search with SearchWP.

We hope this article helped you learn how to easily add Google Search to a WordPress site. You may also want to see our beginner’s guide on how to get my WordPress site listed on Google and our tips for using Google Search Console to grow website traffic.

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.

The post How to Add Google Search in a WordPress Site (The Easy Way) first appeared on WPBeginner.

How to Add Excerpts to Your Pages in WordPress (Step by Step)

Are you looking for a way to add excerpts to your pages in WordPress?

Excerpts are short extracts from your content that can add a description, summary, or small details about a post or page. By default, excerpts are only available for posts in WordPress.

In this article, we will show you how to easily add excerpts to your pages in WordPress, step-by-step.

Add Excerpts to Your Pages in WordPress

Why Add Excerpts to Pages in WordPress?

WordPress comes with posts and pages as two default content types. Posts are displayed in reverse chronological order (latest to oldest) on your blog or homepage.

Pages, on the other hand, are stand-alone content not published in a time-specific order. They are typically used for one-off content like your about us or contact page.

Sometimes, you may need to display excerpts for your pages. For example, this can be handy if you have built a WordPress website using only pages.

Excerpts can provide a better overall user experience by making it easier for visitors to browse through your content and see a summary of your pages.

Having said that, let’s take a look at how to add excerpts to your pages in WordPress and display them on your website. You can use the quick links below to jump between different methods:

How to Add Excerpts to Pages in WordPress

You can enable page excerpts in WordPress by adding custom code to your theme’s functions.php file.

However, the smallest error while typing the code can break your website, and if you switch to a different theme or update it, then you will have to add the code all over again.

That is where WPCode comes in. It is the best WordPress code snippets plugin on the market that makes it safe and easy to add custom code to your website.

First, you must install and activate the WPCode plugin. For detailed instructions, see our step-by-step guide on how to install a WordPress plugin.

Note: WPCode has a free plan that you can use for this tutorial. However, upgrading to the pro version will give you access to a cloud library of code snippets, smart conditional logic, and the CSS snippet option.

Upon activation, visit the Code Snippets » + Add Snippet page from the WordPress dashboard. Here, click the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can start by adding a name for the snippet. This name is only for your identification and won’t be displayed on your website’s front end.

Next, select the ‘PHP Snippet’ option from the dropdown menu on the right.

Choose the PHP Snippet option for the page excerpts code

Now, you must add the following custom code into the ‘Code Preview’ box:

add_post_type_support( 'page', 'excerpt' );

Once you do that, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

The custom code will be automatically executed on your website once you activate the snippet.

Choose insertion method

After that, scroll back to the top of the page and toggle the ‘Inactive’ switch to ‘Active’.

Finally, click the ‘Save Snippet’ button to store your settings.

Click the Save Snippet button for the page excerpts code

Now open the page where you want to add an excerpt in the WordPress block editor.

Once you do that, you will notice an ‘Excerpt’ tab in the block panel on the right side of the screen.

Here, you can easily expand the tab and add an excerpt for your WordPress page.

Add page excerpts in the Excerpts tab in the block panel

Once you do that, don’t forget to click the ‘Update’ or ‘Publish’ button to store your changes.

Now, simply repeat the process for all the WordPress pages where you want to add excerpts.

How to Display Page Excerpts in WordPress

Now that you have added the excerpt functionality to your pages, it is time to actually display these excerpts on your WordPress site.

To do this, you will need to add a shortcode to your widget area or page.

First, you must install and activate the Display Posts plugin. For more details, see our beginner’s guide on how to install a WordPress plugin.

This plugin will enable a shortcode that displays 10 recent pages with their title, excerpt, and a continue reading link.

If you didn’t enter a custom excerpt for a page, then the plugin will automatically generate an excerpt for the page with the default length of 55 words.

Method 1: Display Page Excerpts on a WordPress Page

Upon activation, you must create a new page where you want to display a list of your pages and their excerpts.

Once you are there, click the add block ‘+’ button to open the block menu and add the Shortcode block. Next, paste the following shortcode into the block itself:

[display-posts post_type="page" include_excerpt="true" excerpt_more="Continue Reading" excerpt_more_link="true"]

Add the page excerpt shortcode in the block editor

Finally, click the ‘Update’ or ‘Publish’ button to store your settings.

Now, just visit your WordPress site to view the list of page excerpts.

Preview of page excerpts on a page

Method 2: Display Page Excerpts in the WordPress Sidebar

If you want to display page excerpts in the WordPress sidebar, then you must visit the Appearance » Widgets page from the WordPress dashboard.

Note: If you don’t see the ‘Widgets’ menu tab on your dashboard, then it means you are using a block theme. In that case, you can skip to the next method.

Here, click the add block ‘+’ button to expand the block menu on the left. Then, add the Shortcode block to the sidebar area.

Add page excerpts shortcode in a widget area of your choice like the Sidebar

After that, copy and paste the following shortcode into the block:

[display-posts post_type="page" include_excerpt="true" excerpt_more="Continue Reading" excerpt_more_link="true"]

Finally, click the ‘Update’ button to store your settings.

Now, you can visit your WordPress blog to view the page excerpts.

Preview of page excerpts in the WordPress sidebar

Method 3: Display Page Excerpts in the Full Site Editor

If you are using a block theme, then you must visit the Appearance » Editor page from the WordPress admin sidebar.

This will open the full site editor, where you must choose the page where you want to display a list of page excerpts.

Choose a page to edit in the full site editor

Next, click the add block ‘+’ button on the screen to add the Shortcode block.

Then, copy and paste the following shortcode into it:

[display-posts post_type="page" include_excerpt="true" excerpt_more="Continue Reading" excerpt_more_link="true"]

Add page excerpts shortcode in the full site editor

Finally, click the ‘Save’ button to store your settings.

Now, go ahead and visit your website to view the list of page excerpts.

Page excerpts preview in the WordPress block theme

Bonus: Display Post Excerpts in WordPress

Other than pages, it is also a good idea to show post excerpts on your WordPress blog.

By default, WordPress shows your full-length posts on the homepage, archives page, or blog page. This means a lot of scrolling, which can provide a negative user experience to visitors who want to browse through your website quickly.

As your blog grows, the list of your older posts will also be pushed to other pages and get fewer views. That is why you should consider showing post excerpts on your blog or archives page.

An example of post excerpts in a WordPress theme

If you are using a classic theme, then you can add post excerpts by visiting the Appearance » Customize page from the WordPress admin sidebar.

Once the customizer opens up, expand the ‘Blog’ tab in the left column of the screen. This will open some new settings where you can scroll down to the ‘Post Content’ section and click on the ‘Excerpt’ option.

Adding post excerpts to your WordPress website

However, keep in mind that these settings can differ based on the theme that you are using.

If your theme does not support excerpts, then you can use custom code or page builders like SeedProd to add post excerpts to your blog.

Adding blog excerpts to a WordPress theme

For detailed instructions, see our tutorial on how to display post excerpts in WordPress themes.

We hope this article helped you learn how to add excerpts to your pages in WordPress. You may also want to see our guide on how to choose the best website builder or our expert pick of the best live chat software.

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.

The post How to Add Excerpts to Your Pages in WordPress (Step by Step) first appeared on WPBeginner.

11 Useful WordPress Code Snippets for Beginners (Expert Pick)

Are you looking for some WordPress code snippets to use on your website?

Adding code snippets to your WordPress site allows you to build unique designs and functionalities that may not be possible with themes and plugins. Snippets can also improve security on your website and make the admin dashboard more user-friendly.

In this article, we will share with you our list of the most useful WordPress code snippets for beginners.

Useful WordPress Code Snippets for Beginners

Why Add Code Snippets in WordPress?

If you have a WordPress website, then adding some useful code snippets to your theme files or a code snippets plugin can help you unlock limitless customization and make your site stand out.

You can use custom code to tailor some specific elements on your website. For example, you might change the text selection color in WordPress by adding a simple CSS code snippet.

As a beginner, adding some useful code snippets can also enhance the performance and speed of your site by reducing the need for multiple plugins.

Other than that, snippets can help you expand your coding skills and use the vast library of code snippets that are shared by the WordPress community for free.

Having said that, let’s take a look at some of the most useful WordPress code snippets for beginners. You can use the quick links below to jump to different parts of our tutorial:

1. Allow SVG File Upload

SVG (Scalable Vector Graphics) is a file format that defines vector graphics using the XML markup language. This format allows you to enlarge images without losing any quality.

SVG image quality loss

These files are smaller and more lightweight than JPEG or PNG, helping you boost your website speed.

However, WordPress does not allow SVG file uploads by default because SVGs can contain malicious code that compromises site security.

With that in mind, if you still want to upload SVG files on your website, then you can add the following code snippet to your site:

/**
 * Allow SVG uploads for administrator users.
 *
 * @param array $upload_mimes Allowed mime types.
 *
 * @return mixed
 */
add_filter(
	'upload_mimes',
	function ( $upload_mimes ) {
		// By default, only administrator users are allowed to add SVGs.
		// To enable more user types edit or comment the lines below but beware of
		// the security risks if you allow any user to upload SVG files.
		if ( ! current_user_can( 'administrator' ) ) {
			return $upload_mimes;
		}

		$upload_mimes['svg']  = 'image/svg+xml';
		$upload_mimes['svgz'] = 'image/svg+xml';

		return $upload_mimes;
	}
);

/**
 * Add SVG files mime check.
 *
 * @param array        $wp_check_filetype_and_ext Values for the extension, mime type, and corrected filename.
 * @param string       $file Full path to the file.
 * @param string       $filename The name of the file (may differ from $file due to $file being in a tmp directory).
 * @param string[]     $mimes Array of mime types keyed by their file extension regex.
 * @param string|false $real_mime The actual mime type or false if the type cannot be determined.
 */
add_filter(
	'wp_check_filetype_and_ext',
	function ( $wp_check_filetype_and_ext, $file, $filename, $mimes, $real_mime ) {

		if ( ! $wp_check_filetype_and_ext['type'] ) {

			$check_filetype  = wp_check_filetype( $filename, $mimes );
			$ext             = $check_filetype['ext'];
			$type            = $check_filetype['type'];
			$proper_filename = $filename;

			if ( $type && 0 === strpos( $type, 'image/' ) && 'svg' !== $ext ) {
				$ext  = false;
				$type = false;
			}

			$wp_check_filetype_and_ext = compact( 'ext', 'type', 'proper_filename' );
		}

		return $wp_check_filetype_and_ext;

	},
	10,
	5
);

You can add this code to your theme’s functions.php file or use a code snippets plugin like WPCode. Later on in this article, we will show you exactly how to do this.

For more detailed instructions, you can see our tutorial on how to add SVG image files in WordPress.

2. Disable the WP Admin Bar

By default, WordPress shows an admin bar at the top of your website to all the logged-in users like subscribers, authors, editors, and any other user roles.

This admin bar can direct them to your WordPress dashboard, where they can make any changes to your site depending on their user permissions.

However, it can be a bit distracting when you are looking at the front end of your website because it can sometimes overlap with design elements like the header.

The WordPress admin bar

To disable the WP admin bar, simply add the following PHP code snippet to your WordPress site:

/* Disable WordPress Admin Bar for all users */
add_filter( 'show_admin_bar', '__return_false' );

Upon code execution, the admin bar won’t display on the website’s front end.

However, if you want the admin bar to be removed for everyone but the administrator, then you can see our tutorial on how to disable the WordPress admin bar for all users except administrators.

3. Remove WordPress Version Number

WordPress displays the current WordPress version number on your website for tracking.

Remove WordPress version number

However, sometimes, this footprint can cause security leaks by telling the hackers about the WordPress version in use. The hackers can then target known vulnerabilities in specific versions.

To remove the version number, add the following code snippet to your website:

add_filter('the_generator', '__return_empty_string');

Once you do that, hackers will not be able to guess your WordPress version with automatic scanners and other less sophisticated attempts.

For more detailed instructions, you can see our tutorial on the right way to remove the WordPress version number.

RSS feeds allow users to receive regular updates about your WordPress blog with a feed reader like Feedly.

This can help promote your content and drive more traffic to your site. By adding featured images or thumbnails next to the posts in the RSS feeds, you can make the feed visually appealing and further improve the user experience.

Feed with post thumbnails preview

You can easily show posts thumbnails in your RSS feeds by adding the following useful WordPress code snippet:

/**
 * Add the post thumbnail, if available, before the content in feeds.
 *
 * @param string $content The post content.
 *
 * @return string
 */
function wpcode_snippet_rss_post_thumbnail( $content ) {
	global $post;
	if ( has_post_thumbnail( $post->ID ) ) {
		$content = '<p>' . get_the_post_thumbnail( $post->ID ) . '</p>' . $content;
	}

	return $content;
}

add_filter( 'the_excerpt_rss', 'wpcode_snippet_rss_post_thumbnail' );
add_filter( 'the_content_feed', 'wpcode_snippet_rss_post_thumbnail' );

This can make your feed more engaging and bring back visitors to your site.

For more detailed information, please see our tutorial on how to add post thumbnails to your WordPress RSS feeds.

5. Disable Automatic Update Emails

By default, WordPress sends you an email notification every time it automatically updates any plugins, themes, or the core itself.

This can get super annoying if you have multiple WordPress sites and are constantly seeing these notifications upon opening your email account.

Email notification preview after an auto-update

In that case, you can easily disable automatic update emails by adding the following PHP code snippet to your website:

// Disable auto-update emails.
add_filter( 'auto_core_update_send_email', '__return_false' );

// Disable auto-update emails for plugins.
add_filter( 'auto_plugin_update_send_email', '__return_false' );

// Disable auto-update emails for themes.
add_filter( 'auto_theme_update_send_email', '__return_false' );

Once you do that, you won’t receive any notifications for plugin or theme auto updates.

For detailed instructions, see our step-by-step tutorial on how to disable automatic update email notifications in WordPress.

6. Change ‘Howdy, Admin’ in the Admin Bar

When you log in to your WordPress dashboard, you will be greeted with a ‘Howdy’ followed by your display name at the top right corner of the screen.

This greeting may not sound natural to you or look outdated, or even a bit annoying.

Change Howdy in the admin bar

You can easily change the greeting in the admin bar by adding the following code snippet to your WordPress site:

function wpcode_snippet_replace_howdy( $wp_admin_bar ) {

	// Edit the line below to set what you want the admin bar to display intead of "Howdy,".
	$new_howdy = 'Welcome,';

	$my_account = $wp_admin_bar->get_node( 'my-account' );
	$wp_admin_bar->add_node(
		array(
			'id'    => 'my-account',
			'title' => str_replace( 'Howdy,', $new_howdy, $my_account->title ),
		)
	);
}

add_filter( 'admin_bar_menu', 'wpcode_snippet_replace_howdy', 25 );

Once you add the code, you must also add a greeting of your liking next to the $new_howdy = line in the code.

For more information, you can see our tutorial on how to change or remove ‘Howdy Admin’ in WordPress.

7. Disable XML-RPC

XML-RPC is a core WordPress API. It allows users to connect to their websites with third-party services.

For instance, you will need to enable XML-RPC if you want to use an automation tool like Uncanny Automator or a mobile app to manage your website.

However, if you don’t want to use any of these functionalities, then we recommend disabling XML-RPC to prevent hackers from gaining access to your website.

Hackers can use these vulnerabilities to find your login credentials or launch DDoS attacks.

To disable XML-RPC, you can use the following code snippet on your website:

add_filter( 'xmlrpc_enabled', '__return_false' );

If you need more information, then you can see our tutorial on how to disable XML-RPC in WordPress.

8. Disable Automatic Trash Emptying

WordPress deletes anything that has been in the trash for more than 30 days, including posts, pages, and media files.

However, some users may not want to empty their trash automatically so they can recover deleted files at any time.

View trashed posts

In that case, you can add the following code snippet to your WordPress site:

add_action( 'init', function() {
    remove_action( 'wp_scheduled_delete', 'wp_scheduled_delete' );
} );

Upon adding this code, you will now have to manually empty your trash. For more details, you can see our tutorial on how to limit or disable automatic trash emptying in WordPress.

9. Change Excerpt Length

Excerpts are the first few lines of your blog posts displayed under the post headings on your WordPress home, blog, or archives page.

You may want to shorten your excerpt length to create a sense of intrigue among users and encourage them to click on the post to find out more. Similarly, you can also increase the length to give more context and key information to readers without having to click on the post.

Change excerpt lengths

To change the excerpt length, just add the following code snippet to your website:

add_filter(
	'excerpt_length',
	function ( $length ) {
		// Number of words to display in the excerpt.
		return 40;
	},
	500
);

By default, this snippet will limit the excerpt to 40 words, but you can adjust the number on Line 5 to whatever works best for your blog.

For more information, see our beginner’s guide on how to customize WordPress excerpts.

10. Disable Site Admin Email Verification

By default, WordPress sends an admin verification email to site administrators every few months to verify if the email they use is still correct.

However, sometimes this notice can be sent to you more often than necessary, which can be annoying.

Administration email verification

Fortunately, you can disable the admin email verification notice by adding the following code snippet to your WordPress site:

add_filter( 'admin_email_check_interval', '__return_false' );

For detailed instructions, check our tutorial on how to disable the WordPress admin email verification notice.

11. Disable Automatic Updates

WordPress automatically updates its core software, plugins, or themes to reduce security threats, malware infections, website breaches, and data theft.

However, automatic updates can sometimes introduce compatibility issues or break your website in rare situations.

In that case, you can use the following code snippet to disable automatic updates:

// Disable core auto-updates
add_filter( 'auto_update_core', '__return_false' );
// Disable auto-updates for plugins.
add_filter( 'auto_update_plugin', '__return_false' );
// Disable auto-updates for themes.
add_filter( 'auto_update_theme', '__return_false' );

This will disable all the WordPress automatic updates for the core software, themes, and plugins. For detailed information, see our tutorial on how to disable automatic updates in WordPress.

How to Add Code Snippets in WordPress (Easy Method)

Now that you know the most useful WordPress code snippets for beginners, you can easily add them to your theme’s stylesheets or functions.php file.

However, remember that the smallest error while typing the code can break your site and make it inaccessible. Plus, if you switch to a different theme, then all your custom code will be lost and you will have to add it again.

That is why we always recommend using WPCode.

WPCode - Best WordPress Code Snippets Plugin

It is the best WordPress code snippets plugin on the market that makes it super safe and easy to add custom code to your website.

Plus, the plugin also comes with a library of over 900 code snippets, including all the ones that we have mentioned above. For more information, see our complete WPCode review.

Code Snippets in WPCode

First, you need to install and activate the WPCode plugin. For detailed instructions, see our tutorial on how to install a WordPress plugin.

Note: There is also a free WPCode plugin that you can use. However, upgrading to the premium plugin will give you access to a cloud-based snippets library, code revisions, and more.

Upon activation, visit the Code Snippets » + Add Snippet page from the WordPress dashboard.

This will take you to the snippet library, where you can add custom code to your website by clicking the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet) option.

However, if you want to use a premade code snippet, then you can simply click the ‘Use Snippet’ button under that option.

Click the Use Snippet button under a premade code snippet

If you are adding a custom code snippet, then you simply need to paste it into the ‘Code Preview’ box.

Then, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode. The code will be automatically executed on your website upon snippet activation.

Choose an insertion method

Finally, visit the top of the page and toggle the inactive switch to active. After that, just click the ‘Update’ button to store your settings.

You have now successfully added the code snippet to your WordPress site.

Activate and update the code snippet

For more detailed instructions, see our beginner’s guide on how to easily add custom code in WordPress.

Frequently Asked Questions About WordPress Code Snippets

Here is a list of some questions frequently asked by our readers about using custom code and code snippets in WordPress.

How do I display code on my WordPress site?

If you write blog posts about technical topics, then adding code snippets to your posts can be useful. To do this, you must open the page/post where you want to display the code snippet and click the add block ‘+’ button.

Once you do that, just insert the Code block from the block menu and then add your custom code into the block itself.

Add the code block in WordPress

Finally, click the ‘Publish’ or ‘Update’ button at the top to store your changes.

The code snippet will now be displayed on your WordPress site. For detailed instructions, see our tutorial on how to easily display code on your WordPress site.

How do I create a WordPress website from scratch without coding?

If you want to create a website from scratch without using any code, then you can use SeedProd.

It is the best WordPress page builder on the market that lets you create custom themes and landing pages without any coding.

SeedProd Website and Theme Builder

The plugin comes with 300+ premade templates, a drag-and-drop builder, and numerous advanced blocks that allow you to build an attractive website with just a few clicks.

For details, you can see our tutorial on how to create a landing page in WordPress.

Where can I get WordPress code snippets?

You can use WPCode’s library to access over 900 code snippets that you can add to your website easily.

However, if you are not using WPCode, then you can also get prewritten code snippets from websites like Stack Overflow, CodePen, or GenerateWP.

We hope this article helped you find the most useful WordPress code snippets for beginners. You may also want to see our tutorial on how to easily add JavaScript to WordPress pages or posts and our top picks for the best WordPress theme builders on the market.

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.

The post 11 Useful WordPress Code Snippets for Beginners (Expert Pick) first appeared on WPBeginner.

How to Edit a WordPress Website (Ultimate Guide)

Are you a new WordPress.org user who wants to learn how to edit your WordPress site?

Here at WPBeginner, we have helped millions of beginners build their websites using WordPress, which is the most popular website builder on the market. If you need help with editing your website, then you have come to the right place.

In this article, we will show you the basics of editing a WordPress website.

How to Edit a WordPress Website (Ultimate Guide)

An Overview of Ways to Edit a WordPress Site

As an open-source content management system, WordPress has a lot of features to build and edit your website.

If you installed WordPress recently, then you may have come across Gutenberg, which is WordPress’s drag-and-drop block editor that allows you to customize a page or post. This feature is pretty easy and beginner-friendly.

The Gutenberg block editor interface

You may have also seen the Full Site Editor.

This is an extension of Gutenberg that lets you use the block editor to customize block-based WordPress themes.

The WordPress Full Site Editor

That said, if you use a classic, non-block WordPress theme, then the FSE won’t be available to you. Instead, you will have to use the WordPress Theme Customizer.

This feature doesn’t come with a drag-and-drop function, so it’s not as user-friendly. You have to edit your theme using some menu settings in the left-hand panel.

Using the WordPress Theme Customizer to edit a transportation and logistics website

If you need more customization options that aren’t available in WordPress’s built-in features, then you can install a page builder plugin like SeedProd.

This is what we usually recommend to WordPress beginners. Like Gutenberg, SeedProd has a drag-and-drop feature. However, it offers more ways to get creative, like animation effects and more content block options to build your pages.

Editing the online coaching business theme in SeedProd

Some WordPress users also use the Classic Editor. It’s WordPress’s legacy page and post editor that looks a bit like a document editor.

This feature is no longer enabled by default in the latest WordPress versions. However, some people still use it because they are more familiar with it and want to keep their current website designs.

The Classic Editor Interface

In this article, we will show you how to edit different parts of your WordPress website using the editors we’ve mentioned.

We will also assume that you have WordPress installed and set up already. Otherwise, you will need a WordPress hosting plan, domain name, and WordPress installation.

Want to skip to a specific section in this tutorial? Feel free to use these quick links below:

How to Edit a WordPress Theme

One of the first things you should do after installing WordPress is to choose and customize your theme. We will show you 3 ways to do that.

Customizing a Block Theme With the Full Site Editor

Full Site Editing was introduced in WordPress 5.9. It’s designed to make it easy to edit WordPress block themes using the block editor.

One tell-tale sign that you are using a block WordPress theme is you will see Appearance » Editor in your WordPress admin area. If you see Appearance » Customize instead, then you can skip to using the Theme Customizer.

Clicking Appearance Editor in the WordPress admin

To use the Full Site Editor, you will need to have a block theme installed. You can find plenty of them in our list of the best block WordPress themes for Full Site Editing.

If you want to find some free options, go to Appearance » Themes. Then, click ‘Add New Theme.’

Adding a new WordPress theme in the admin area

After that, just switch to the ‘Block Themes’ tab.

You will then see dozens of block themes on your screen. For installation instructions, check out our step-by-step guide on how to install a WordPress theme.

Finding WordPress block themes in the admin area

Once you have the theme installed, you must go to Appearance » Editor.

Now, you will see the main Full Site Editing dashboard. You can then edit your theme’s navigation menu, styles, pages, templates, and patterns.

We will discuss these topics in the rest of the tutorial, but we will show you briefly how to change the style of your theme.

To do this, click the ‘Styles’ menu.

Clicking Styles in the Full Site Editing interface

Now, you will see a list of the color scheme and typography pairings provided by the theme.

Every time you click on a style, the interface will preview it for you.

Choosing a theme style in the Full Site Editor

Once you are satisfied with your choice, just click ‘Save.’ Alternatively, you can create a custom style.

You can learn more about this and other ways to use the Full Site Editor in our beginner’s guide to WordPress Full Site Editing.

Customizing a Classic Theme With the Theme Customizer

If you use a classic WordPress theme, then you will work with the Theme Customizer to edit it. Simply head to Appearance » Customize from the WordPress admin area to access it.

Opening the WordPress theme customizer

Now, what you can customize here varies by the theme you are using.

For instance, if you have the Astra theme, then you can customize the style of your entire website, header, footer, sidebar, page, logo, and so on.

For this reason, we recommend reading your theme’s documentation for more instructions.

What the Theme Customizer looks like for Astra theme

Our guide on the Theme Customizer can give you more detailed pointers.

Once you’ve made your changes, you can preview the website in different screen resolutions. Then, you can hit the ‘Publish’ button at the top to make your edits live.

Publishing a classic WordPress theme in the Theme Customizer

One downside of the Theme Customizer is its user experience isn’t as flexible or easy as the block editor. If you feel this way, then we recommend using the next method instead.

Customizing a WordPress Theme With a Page Builder Plugin

Many WordPress users who aren’t satisfied with the platform’s built-in design features use a page builder to edit their site. This is a WordPress plugin that can replace the default editor for designing different parts of your website.

Most page builders come with a drag-and-drop functionality, so they are just as easy to use as the block editor. What’s more, they come with more page blocks and templates to personalize your website.

Out of all the page builders we’ve tried, we find SeedProd to be the best. It comes with 300+ templates for various industry categories, from eCommerce and accommodation to services.

SeedProd Website and Theme Builder

Note: While SeedProd comes in a free version, we recommend upgrading to the Pro plan to access the Theme Builder. This is what we will use in this tutorial.

To use SeedProd, you will need to install the WordPress plugin first. After that, go to SeedProd » Settings to activate your Pro plan license. Simply insert your license key and click ‘Verify Key’ to complete this step.

Verifying SeedProd Pro's license key

Next, switch to SeedProd » Theme Builder.

Just click ‘Theme Template Kits‘ to view your theme options.

Accessing SeedProd's Theme Template Kits

As you can see, there are many theme template kits available, from online stores to service sites. Feel free to use the filtering and sorting settings to find the right one for your needs.

Once you’ve made your choice, just hover over the theme template and click the orange checkmark button to use it.

Choosing a theme template kit in SeedProd

Now, just go back to the Theme Builder page and select a theme template you’d like to edit.

For demonstration purposes, we will show you how to edit the style of your SeedProd theme template. To do this, locate the ‘Global CSS’ theme template, hover over it, and click ‘Edit Design.’

Editing a theme template kit's Global CSS in SeedProd

You are now inside the SeedProd page builder and can customize your theme template’s style. Here, you can change your website’s colors, fonts, backgrounds, buttons, forms, and layout.

Let’s see how to change the theme’s default font. To do this, open the ‘Fonts’ menu. Then, just choose one of SeedProd’s many font and color options for the heading and body text.

All the changes you make will show up automatically in the right-side preview.

Changing a SeedProd theme template kit font in the Global CSS theme template

Once you are happy with the style, just click ‘Save’ to make these changes official.

Then, you can go back to SeedProd » Theme Builder and turn on the ‘Enable SeedProd Theme’ toggle in the top right corner.

Enabling the SeedProd theme template kit in WordPress

For more information about editing WordPress themes with SeedProd, you can see our guide on how to easily create a custom WordPress theme.

How to Edit a WordPress Page or Post

If you have updated WordPress to the latest version, then most likely, you will use the Gutenberg block editor to edit a page or post.

You can create a new page by going to Pages » Add New Page. This will automatically make an entirely blank page and direct you to the block editor.

On the other hand, if you want to edit an existing page, like the homepage or blog page, then you can go to Pages » All Pages. Hover your cursor over the page you want to edit, and then click ‘Edit.’

Clicking the Edit button to edit an existing WordPress page

Alternatively, there is also the Quick Edit feature.

This allows you to modify the page’s title, URL slug, and last modified date.

Clicking the Quick Edit button in the WordPress Pages page

You can do various things with the Quick Edit feature.

Examples include setting a password for the page, making it private, assigning it as a parent page, changing the page template, allowing/disallowing comments, and changing the page status.

The Quick Edit feature for WordPress pages

To create a new post, simply head to Posts » Add New Post to make a new blank post and edit it using the block editor.

Like before, you can edit an existing WordPress blog post by hovering your cursor over the selected post and clicking ‘Edit.’

The WordPress Posts interface in the WordPress admin area

The Quick Edit feature for posts is similar but with some minor differences.

Here, you can also add tags, allow/disallow pings, and make the post sticky (featured on your website).

The Quick Edit feature for WordPress blog posts

Once you have opened up a WordPress page or post, there are many things you can do in the block editor.

Typically, you will start by clicking the ‘+’ add block button in the top left corner.

This is where you will find all the available blocks from WordPress and the plugins you use.

Opening the block inserter library in WordPress

You can then drag and drop a block to the main editing area.

After that, you can use the block’s toolbar and settings sidebar to configure the block’s style, dimensions, spacing, and more.

The block settings sidebar in WordPress

If you have installed a WordPress plugin, then you may also see some settings below the editing interface.

For instance, the All in One SEO plugin will show you a section where you can optimize the page or post’s meta title and description for search engines.

The AIOSEO settings in the WordPress block editor

We have plenty of guides for you to learn more about editing posts and pages, so be sure to check them out:

How to Edit a WordPress Page or Post With Classic Editor

If you want to use the Classic Editor, then you will need to enable it. You can read our article on how to disable Gutenberg and activate the Classic Editor to do this.

After that, just create a new post or page by going to Posts » Add New Post or Pages » Add New Page, and the Classic Editor will show up on your screen.

The WordPress classic editor

Unlike the block editor, you won’t add blocks to insert content into your page or post. Instead, you can only type text, format it using the controls at the top of the editing panel, and add media files to your content by clicking on the ‘Add Media’ button.

At the bottom and the sides of the editing interface, there are settings to publish the page/post, set the page or post’s categories/tags, upload a featured image, and so on.

You can also switch between the visual and text editing modes. With the second editor, you can modify the post or page’s HTML code.

The text editing mode in the WordPress classic editor

How to Edit a WordPress Page With a Page Builder

If you already use a page builder like SeedProd to edit your theme, then you can use it to edit a page as well. This way, you can maintain your design’s consistency throughout all of your pages.

You will need to create a new page and open the block editor. If SeedProd is active, then you will see a button at the top that says, ‘Edit with SeedProd.’ Go ahead and click on it.

You can also do this with an existing page. However, do note that the content will not be transferred over, and you will have to create the page from scratch.

Clicking the Edit with SeedProd button in the WordPress block editor

In the page builder, you will see that the SeedProd theme’s header and footer have been added. All you need to do is start building the page.

First, choose one of the 8 layouts to use on the page.

Choosing a layout for the section in a SeedProd theme template

On the left-hand side, you will find all the blocks and sections that you can drag and drop onto the right-hand side, which is the template preview.

You can use these to insert content into the page.

SeedProd's block library

Whenever you click a block or a section, the left-hand side will show the available settings to customize the element.

In the screenshot below, you can see that clicking on the Text block will make the block settings appear. You can customize the text, insert dynamic content, edit the HTML, change the alignment, and so on.

Customizing SeedProd's text block settings

Once you are done editing the page, don’t forget to click ‘Save’ to make the changes live.

For more details, just see our guide on how to create a custom page in WordPress.

If you want to create a custom landing page from scratch, then you can also do that with SeedProd. All you need to do is go to SeedProd » Landing Pages. Then, click the ‘+ Add New Landing Page’ button.

Create a new landing page in SeedProd

For more information, check out our tutorial on how to create a custom landing page.

Alternative: Thrive Architect is another great page builder option for designing attractive and conversion-focused landing pages.

You may also want to edit the WordPress header, footer, sidebar, and other parts of your theme template.

These are sections on your site that are not part of the main page or post content. However, they are essential for giving additional information or helpful navigation.

How you can edit these sections depends on what theme you are using, so let’s go through each option.

How to Edit a Block Theme’s Header, Footer, and Other Template Parts

If you have a block theme, then you can use the Full Site Editor to edit your theme’s header and footer.

In the Full Site Editor, a header and footer are considered template parts. These are also known as WordPress patterns (a set of reusable blocks) that appear throughout your website.

Other examples of a template part include the comment section and the post meta.

For the sake of example, we will show you how to edit your WordPress header, but you can repeat these steps with other template parts.

First, go to Appearance » Editor. Once you are in the Full Site Editor, just click ‘Patterns.’

Clicking the Patterns menu in the Full Site Editor

You will now see a list of patterns provided by your WordPress theme.

Go ahead and scroll down to the Template Parts section. Then, select ‘Header’ and click on the Header template part.

Opening the header template part in the WordPress Full Site Editor

Now, you need to click the pencil button next to the Header text.

This will open the block editor.

Clicking the pencil button to edit the header using the Full Site Editor

The block editor works the same way with template parts as it does with pages and posts. You can add various blocks to the header, configure the block, and update the changes when you are done.

Headers usually include a Site Logo (or the favicon), so feel free to add that here, too.

Adding the Site Logo block to the header in the Full Site Editor

If you want to completely change how the header looks but don’t know where to start, click the ‘+’ add block button in the top left corner.

Then, navigate to the ‘Patterns’ tab and click ‘Headers.’ You will find many ready-to-use header layouts there.

Finding WordPress header patterns in the Full Site Editor

For more information, see our guide on how to customize your WordPress header.

Once you are done changing the header, click ‘Save.’ Since the header is a synced template part, all the changes you make here will apply across all pages that use the header.

Now, if you want to create a new header or any other template parts rather than editing the existing ones, you can go back to the ‘Patterns’ page. After that, click the ‘+ Create pattern’ button and select ‘Create template part.’

Creating a new template part in the Full Site Editor

In the popup, give the template part a name and select the type of template part.

Then, click ‘Create.’ You will then be directed to the block editor and you can edit the template part like usual.

The Create template part popup in the WordPress Full Site Editor

For more details, you can see our complete guide to WordPress full site editing.

How to Edit a WordPress Header, Footer, and Other Widget-Ready Areas in a Classic Theme

In a classic theme, a WordPress widget is basically a block that you can add to widget-ready areas, like headers, footers, sidebars, and so on.

Every classic WordPress theme has different widget-ready areas. Some may include a sidebar, and some may not. So be sure to check your theme’s documentation for more information.

To use widgets, you have to go to Appearance » Widgets. Here, you can add, configure, and remove blocks in the available widget-ready areas.

Adding the FlipBox widget to a sidebar or similar section

You can read more information about widgets in our how to add and use widgets in WordPress article.

Also, check out our guide on the difference between widgets and blocks to understand more about this feature.

How to Edit a WordPress Header, Footer, and Other Template Parts With a Page Builder

One of the benefits of using a page builder is you will have more options to customize headers, footers, sidebars, and other parts of your theme.

If you use SeedProd, you can go to SeedProd » Theme Builder. We will assume that you have installed a theme template kit from earlier.

The kit usually includes various theme templates. This may be a built-in page template, like a 404 or single post, or a part of a page, like a header, footer, pricing tables, and so on.

Go ahead and hover over a theme template. Then, click ‘Edit Design.’

Editing the header theme template in SeedProd

Now, you can edit the header the same way as you would with a page.

Let’s say you want to add your social media links here. What you can do is hover over the header until the blue border appears and click the ‘+ Add Row’ button. Then, go ahead and select a row layout.

In our example, we want to add one more column so that the header can fit the image, menu, and social media links. That means we will need three columns in one row.

Choosing a row layout in SeedProd

You can then drag and drop the blocks from the top row to the new row.

After that, just delete the top row so that your new row becomes the new header.

Deleting a previous row in a SeedProd section

Now, just look for the Social Profiles block in the left-side panel.

Drag it into the right column, and you are done.

Adding the Social Profiles block in the header in SeedProd

For more information about editing template parts, you can read these WordPress tutorials:

How to Edit a Navigation Menu in WordPress

A navigation menu makes it easy for visitors to explore all your content without getting lost on your website. That’s why it’s important to design a menu that shows your essential pages and links to other relevant information.

If you use a block WordPress theme, then you can select the ‘Navigation’ menu from the Full Site Editor page.

Selecting Navigation in WordPress Full Site Editing

Our article on adding custom navigation menus in WordPress can walk you through the rest of the steps.

If you use a classic WordPress theme, then you can go to Appearance » Menus. This is a dedicated page for you to add, arrange, and remove pages/posts and links to your menus.

How to add a WordPress navigation menu to your site or blog

For step-by-step instructions, you can check out our beginner’s guide on how to add a navigation menu in WordPress.

If you use a page builder like SeedProd, then your navigation menu (Nav Menu block) may have been embedded in your header theme template.

The Nav Menu block will already include all of your pages, though you can add new items, too.

First, go to SeedProd » Theme Builder from your WordPress dashboard. Then, find the ‘Header’ theme template and click ‘Edit Design.’

Editing the header theme template in SeedProd

Now, hover over the block that looks like a menu. That should be the ‘Nav Menu’ block.

After that, scroll down on the left panel and click ‘+ Add New Item.’

You can then customize the anchor text, enter the URL, have it open in a new window, and set it as nofollow.

Adding new menu items in SeedProd

Toward the bottom, you can change the links’ font size, spacing, divider, and alignment.

Don’t forget to click ‘Save’ to make the changes live.

Configuring the Nav Menu block in SeedProd

How to Edit a WordPress Site With Code

If you are comfortable with code, then you can also use custom code snippets to edit your WordPress website. That said, we only recommend this method if you have the right technical know-how to avoid breaking your website.

One way you can edit a WordPress site with code is by adding CSS, which is a stylesheet that can change how HTML looks on the front end.

Classic theme users can go to Appearance » Customize and find the ‘Additional CSS’ field in the Theme Customizer.

Here, you can insert CSS code to style different HTML elements like colors and fonts.

This may be handy if your theme’s built-in options aren’t enough for your needs.

Adding custom CSS in WordPress

As for block theme users, you cannot add custom CSS within the Full Site Editor.

Instead, you have to go to the URL below to open the Theme Customizer and find the Additional CSS field. Make sure to replace the domain name with your own.

https://example.com/wp-admin/customize.php

For more details, see our guide on how to fix missing Theme Customizer in WordPress.

Another way to add CSS is with CSS Hero. This plugin makes adding custom CSS to WordPress themes easy, even for beginners. If you are interested in using it, then just check out our CSS Hero review.

How to Edit WordPress Theme Files

At times, some tutorials may require you to edit your WordPress theme files to make changes beyond what your built-in theme features allow. In this case, we recommend:

  • Creating a child theme first. This is like a copy of your WordPress theme that you can safely customize with some coding.
  • Backing up your website. It’s a good measure to do so that you can restore your website to a previous version in case of errors.

Editing a WordPress theme file requires going to your WordPress file directory from the backend. To do this, you will need to open your hosting provider’s file manager or connect to your website with an FTP client.

If you use Bluehost, then you can go to your dashboard and open the ‘Websites’ tab. After that, click ‘Settings’ on the website for which you want to open the theme files.

Opening Bluehost's website settings

Now, simply scroll down to the ‘Quick Links’ section.

Then, click ‘File Manager.’ If you’re not sure where your root folder is, you can check the ‘Document Root’ function to see its path.

Opening Bluehost's file manager

Once inside the file manager, you can go to your website’s root folder (usually named public_html).

Then, head to /wp-content/themes and find your current theme folder.

An example of what the WordPress theme files look like in the Bluehost file manager

After that, you will find all of your WordPress theme files, which you can edit using a text editor.

Here are some things you can do by editing WordPress theme files:

How to Safely Insert Custom Code into WordPress

If you want to add new custom code rather than editing the code that is already within your theme files, then we recommend using WPCode. It’s the best WordPress code snippets plugin for easily inserting and managing custom code snippets.

WPCode - Best WordPress Code Snippets Plugin

With this plugin, you won’t have to worry about accidentally breaking your website. WPCode will let you know if there are errors in the code and deactivate it. Plus, you can create PHP shortcodes for inserting custom content into your website.

To see WPCode in action, you can check out our full WPCode review in the WPBeginner Solution Center.

What Is the Best Way to Edit a WordPress Site for Beginners?

For beginners, we always recommend installing a page builder plugin like SeedProd to edit WordPress websites. The reason is that it’s just as easy to use as the block editor yet gives you much more control over your website design.

If you don’t want to use a plugin, then the next best thing is a block theme with the Full Site Editor. This feature is not entirely developed yet because WordPress is constantly working on the Gutenberg project. But as of now, it’s pretty user-friendly.

The Theme Customizer is not as flexible as the Full Site Editor because it lacks drag-and-drop functionality. That’s why we suggest classic theme users install SeedProd to improve their user experience.

As for coding, we only recommend it if you have created a child theme and backups of your site to avoid errors. But with the WPCode plugin, adding custom code to edit your WordPress site is much safer and won’t cause any errors or break your website.

We hope this article helped you learn how to edit a WordPress website. You may also want to check out our in-depth WooCommerce tutorial to create an online store and the ultimate guide to WordPress SEO.

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.

The post How to Edit a WordPress Website (Ultimate Guide) first appeared on WPBeginner.

How to Add Custom Admin Notices in WordPress (2 Easy Methods)

Often, our readers ask us how they can add custom admin notices in WordPress.

WordPress core, themes, and plugins display admin notices like errors or warnings to users in the dashboard. If you are a WordPress site administrator, then you can also create custom notices to inform your team members of important information about the website.

In this article, we will show you how you can easily add custom admin notices in WordPress.

How to Add Custom Admin Notices in WordPress

Why Add Custom Admin Notices in WordPress?

Admin notices are notifications inside the WordPress admin area that inform users about important information. Examples include errors, warnings, alerts, or success messages related to WordPress core, plugins, or themes.

Admin notice example

While these notifications are a built-in WordPress feature, you can also create custom admin notices for your dashboard.

For instance, let’s say you are working on a WordPress website for clients who are not familiar with the platform. You might add admin notices to display helpful information inside their WordPress admin area.

Some other examples of using custom admin notices include:

  • Letting team members know when the website will be unavailable due to being in maintenance mode.
  • Guiding writers or editors to navigate the editorial workflow in the dashboard if you run a multi-author site.
  • Reminding users of certain do’s and don’ts when managing tasks, content, and media in WordPress.

All in all, custom admin notices can be useful for communicating messages to yourself or other users who work on your website. That being said, you will need to use them wisely, as too many notices can be annoying.

Now, let’s look at how you can add your custom admin notices in WordPress. We will show you two methods, and you can use the quick links below to skip to the one you want to use:

Method 1: Add Custom WordPress Admin Notices With a Plugin

This method uses the WP Custom Admin Interface plugin. It lets you customize your WordPress dashboard to your preferences, including displaying custom admin notices.

The first step is to install and activate the WP Custom Admin interface plugin. For step-by-step instructions, see our guide on how to install a WordPress plugin.

Next, go to Custom Admin Interface » Admin Notice. As you can see, the plugin settings page is quite similar to the Classic Editor.

The WP Custom Admin plugin settings for admin notices

You now need to scroll down and insert your admin notice message.

You can use plain text and/or the shortcode options available for you, which are located above the visual editor.

If you use the second method, then the message will dynamically generate content based on the provided shortcodes. So, if you use the shortcode [WEBSITE_URL], then the shortcode will be replaced with your website’s domain name.

Additionally, feel free to add an image or other media files or stylize the text using the toolbar above the text box.

Inserting the custom admin notice content using WP Custom Admin plugin

Moving down, you can choose the color of your custom admin notice. The default options are:

  • Green for success messages
  • Blue for non-urgent yet important information notices
  • Yellow for warning messages
  • Red for error messages

Another thing you can customize is the notice end date or when the notice should be deactivated. Feel free to leave it blank if there is no expiration date.

You can also make the message dismissable, which is recommended for notifications using green or blue colors. For warnings or errors, you may want to keep displaying them until the problem is solved, depending on the issue.

Finally, you can make the notice visible to everyone or certain users only. If you choose the latter, you can click the ‘+’ button to specify what user roles the notice should be invisible for.

Once you are happy with the custom admin notice, just click ‘Save All Settings.’

Saving the custom admin notice in WP Custom Admin plugin

And that’s it!

To see what the custom admin notice looks like, just go to any page on your WordPress dashboard. The message should be at the top of the screen.

Custom admin notice example made with WP Custom Admin plugin

Method 2: Add Custom WordPress Admin Notices With Code

While the WP Custom Admin Interface plugin is easy to use, it includes a lot of additional features that may be unrelated to your needs. This can feel like overkill if you are only interested in creating custom admin notices.

Furthermore, the WP Custom Admin Interface only allows you to display one custom notice at a time. If you want to show several notices on different pages of your WordPress admin dashboard, then the plugin may not be a suitable option.

Instead, you can manually add a custom admin notice in WordPress using code. This lets you focus only on adding the custom notice without any extra stuff, and you can display multiple notices if needed.

If coding in WordPress sounds scary, don’t worry. We will show you an easy and safe way to insert custom code, which is using WPCode. It’s the best and most beginner-friendly custom code snippet plugin on the market.

With WPCode, you can easily insert and manage code without directly interacting with the WordPress core files. This way, the chances of you breaking your website are zero to none.

WPCode - Best WordPress Code Snippets Plugin

For more information about WPCode, you can check out our WPCode review.

Note: To follow this tutorial, you can use either the free version of WPCode or a premium plan. With WPCode Pro, you will get advanced features to manage your code further, like a testing mode to see how the code works before making any permanent changes.

The first step to using WPCode is to install and activate the plugin. If you need some guidance, then just see our article on how to install a WordPress plugin.

Next, simply go to Code Snippets » + Add Snippet. Under Add Your Custom Code (New Snippet), click on ‘Use snippet.’

Use snippet

Now, go ahead and insert a title for your custom code snippet so that you can easily identify and edit it later if needed. It can be something like ‘Custom Admin Notice.’

Then, change the Code Type to ‘PHP Snippet.’

Once you’ve done that, simply copy and paste the following code into the Code Preview box:

function wpb_admin_notice() {
	echo // Customize the message below as needed
	'<div class="notice notice-warning is-dismissible">
	<p>Important! We will not be publishing any new articles during the holidays. Please save your articles as drafts for the time being.</p>
	</div>'; 
}
add_action( 'admin_notices', 'wpb_admin_notice' );

Here’s what the screen should look like:

The custom admin notice code snippet in WPCode

This code defines a function named wpb_admin_notice() in WordPress. Inside this function, there is an echo statement that outputs a warning message in a stylized box.

Below that statement is <div class="notice notice-warning is-dismissible">. This is a CSS class that specifies the type of admin notice, which, in this case, is a warning. Because of this, the notice box will have a yellow border.

You can also replace the line of code notice-warning with notice-error (red), notice-info (blue), and notice-success (green).

Under the CSS class is the actual notice content. Here, the message informs users that no new articles will be published during holidays and advises them to save articles as drafts for the time being. You can replace the text between the <p> and </p> HTML tags with your own.

The add_action('admin_notices', 'wpb_admin_notice'); line hooks this function to the 'admin_notices' action in WordPress. This means that the warning notice will be displayed in the WordPress admin area, providing important information to all users.

Once you have inserted the code, scroll down to the Insertion section. Make sure the Insertion method is ‘Auto Insert’ and the Location is ‘Admin Only.’

These settings will ensure that the snippet will be automatically executed in the WordPress admin area only.

Choosing Auto Insert and Admin Only in WPCode

After that, just make the code snippet ‘Active’ and click ‘Save Snippet.’

Here’s what the custom admin notice looks like on our test website:

Custom admin notice example made with WPCode

Displaying the Custom Admin Notice Based on the User Role

If you want to create a custom admin notice that is only visible for certain user roles, then you can also do that with WPCode.

Here is a code example:

function wpb_admin_notice_editor() {
    // Get the current admin page
    global $pagenow;
    // Specify the admin pages where the notice should appear
	$admin_pages = [ 'index.php' ];
	// Get the current user
	$user = wp_get_current_user();
    // Check if the current page is in the specified admin pages and the user has the 'editor' role
    if ( in_array( $pagenow, $admin_pages ) && in_array( 'editor', (array) $user->roles ) ) {
		// Display a warning notice for editors
		echo
		'<div class="notice notice-warning is-dismissible">
			<p>Reminder! Do not save published posts as drafts after you update them. Just click the Update button without changing to the draft status. Thanks.</p>
		</div>';
	}
}
// Hook the function to display the notice in the admin area
add_action( 'admin_notices', 'wpb_admin_notice_editor' );

This WordPress code defines the function wpb_admin_notice_editor()that displays a warning notice in the admin area for users with the editor role.

The code first retrieves the current admin page being viewed using global $pagenow;. It specifies that the notice should appear on specific wp-admin pages, such as the dashboard (index.php), through the $admin_pages array.

If you want to make the notice display on other pages of the admin area, simply add the page’s slug, like plugins.php for Plugins and edit.php for Posts and Pages.

Just make sure to separate the slugs with a comma and a single quote, like $admin_pages = [ 'index.php' , 'plugins.php', 'edit.php' ];.

After that, the code gathers information about the currently logged-in user with $user = wp_get_current_user(); .

The code then checks if the current page is in the specified admin pages and if the user has the ‘editor’ role using if ( in_array( $pagenow, $admin_pages ) && in_array( 'editor', (array) $user->roles ) ) {.

If both conditions are met, then it proceeds to display a warning notice.

Here’s what our custom admin notice looks like using the code above:

Personalized custom admin notice example made with WPCode

Creating personalized and targeted custom admin notifications requires some WordPress coding knowledge. If you are interested in diving into this topic, then we recommend reading these guides:

We hope this article has helped you learn how to add custom admin notices in WordPress. You may also want to see our guide on how to code a website or our expert pick for the best WordPress plugins to grow your website.

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.

The post How to Add Custom Admin Notices in WordPress (2 Easy Methods) first appeared on WPBeginner.

How to Display Random Posts in WordPress (Easy Tutorial)

Are you looking for a way to display random posts in WordPress?

Displaying random posts can encourage users to browse through the different articles on your website, resulting in more pageviews and higher user engagement.

In this article, we will show you how to easily display random posts in WordPress.

Displaying random posts in WordPress

Why Display Random Posts in WordPress?

By default, WordPress lists your blog posts in reverse chronological order (from newest to oldest). This allows users to see your latest posts first.

However, most users will not get to see your older articles. For example, if you have been running your WordPress blog for a long time, then your older articles will not be prominently displayed anywhere on the website.

One way to overcome this is by making internal linking a habit. Linking to your older articles in new posts will help users discover them. It will also increase your page views and improve SEO.

Another way around this problem is displaying random posts on your WordPress pages, posts, or sidebar.

This helps users discover content that they may not have found otherwise, improving the overall user experience.

Having said that, let’s see how you can easily display random posts in WordPress. We will cover two methods, and you can use the quick links below to jump to the one you want to use:

Method 1: Display Random Posts in WordPress Using WPCode (Recommended)

If you are looking for an easy and customizable way to display random posts in WordPress, then this method is for you.

Many tutorials will tell you to do this by adding code to your theme’s functions.php file. However, the smallest error while typing the code can break your website and make it inaccessible.

That’s why we recommend using WPCode, which is the best WordPress code snippets plugin on the market. It is the easiest and safest way to add custom code to your website.

First, you need to install and activate the WPCode plugin. For detailed instructions, please see our beginners’ guide on how to install a WordPress plugin.

Note: You can also use the free WPCode plugin for this tutorial. However, upgrading to the Pro version will give you access to a cloud library of code snippets, smart conditional logic, and more.

Upon plugin activation, head over to the Code Snippets » + Add Snippet page from the WordPress admin sidebar.

Once you are there, click the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can start by typing a name for the code snippet.

This title is only there for your reference and won’t be shown on the website’s front end.

After that, you must choose ‘PHP Snippet’ as the ‘Code Type’ from the dropdown menu on the right side of the screen.

Choose PHP Snippet as the code type for displaying random posts

Next, simply copy and paste the following code into the ‘Code Preview’ box:

function wpb_rand_posts() { 
 
$args = array(
    'post_type' => 'post',
    'orderby'   => 'rand',
    'posts_per_page' => 5,
    );
 
$the_query = new WP_Query( $args );
 
if ( $the_query->have_posts() ) {
 
$string .= '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        $string .= '<li><a href="'. get_permalink() .'">'. get_the_title() .'</a></li>';
    }
    $string .= '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
 
$string .= 'no posts found';
}
 
return $string;
} 
 
add_shortcode('wpb-random-posts','wpb_rand_posts');
add_filter('widget_text', 'do_shortcode');

Upon activation, this code will display 5 random posts on your website. You can also change the 'posts_per_page' value to a different number.

Next, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

Even after choosing this mode, you will need to add the [wpb-random-posts] shortcode to your website’s sidebar, page, or post to display random posts.

Keep in mind that this shortcode isn’t a result of the WPCode ‘Shortcode’ feature and is part of the code snippet itself.

Choose an insertion method

Finally, scroll back to the top and toggle the ‘Inactive’ switch to ‘Active’.

After that, simply click the ‘Save Snippet’ button to store your changes.

Save snippet for displaying random posts

Display Random Posts on a WordPress Page or Post

Once you have saved your code snippet, you can display random posts on your website’s page or post using this method.

First, open up a new or existing page/post from the WordPress dashboard.

Next, click the ‘Add Block’ (+) button at the top left corner of the screen to open up the block menu. From here, find and add the Shortcode block to the WordPress page or post.

After that, simply copy and paste the following shortcode into the block:

[wpb-random-posts]

Add shortcode in a page

Finally, click the ‘Publish’ or ‘Update’ button at the top to save your changes.

Now, you can visit your WordPress website to check out the random posts.

Preview for displaying random posts on a page or post

Display Random Posts in the Sidebar as a Widget

If you are using a classic theme, then this method is for you.

First, you need to visit the Appearance » Widgets page from the WordPress admin sidebar.

Once you are there, just click the ‘Add Block’ (+) button at the top left corner of the screen to open up the block menu.

From here, locate and add the Shortcode block in the ‘Sidebar’ tab. Next, copy and paste the following shortcode into the block:

[wpb-random-posts]

Add shortcode for displaying random posts in sidebar widget

Finally, click the ‘Update’ button at the top to save your changes.

Now, you can visit your site to check out the random posts displayed in your WordPress sidebar.

Displaying random posts as a widget

Display Random Posts in a Block Theme

If you are using a block-based theme with the full site editor, then this method is for you.

You can start by visiting the Appearance » Editor page from the WordPress admin sidebar. This will launch the WordPress full site editor.

Once you are there, you need to click on the ‘Add Block’ (+) button at the top left corner and add the Shortcode block to your preferred place on the website.

After that, copy and paste the following shortcode into the block:

[wpb-random-posts]

Add shortcode for random posts in FSE

Finally, click the ‘Save’ button at the top to store your changes.

Now, you can visit your website to see the random list of posts.

Preview for random posts

Method 2: Display Random Posts in the WordPress Sidebar Using the Recent Posts Widget Extended

If you want to display random posts in your WordPress sidebar without using any code, then this method is for you.

First, you need to install and activate the Recent Posts Widget Extended plugin. For instructions, you can see our tutorial on how to install a WordPress plugin.

Once the plugin has been activated, you can simply display random posts in your WordPress sidebar using a block.

Note: The plugin only works for the widget area in classic WordPress themes. If you are using a block theme, then the plugin’s block won’t be available.

Similarly, the plugin doesn’t allow you to display random posts on a WordPress page or post.

To display random posts in the WordPress sidebar, visit the Appearance » Widgets page from the admin dashboard.

Here, click the ‘Add Block’ (+) button at the top left corner of the screen to open up the block menu. Next, find and add the Recent Posts Extended block to the ‘Sidebar’ tab.

This will open up configuration settings for the block. Here, you can start by typing a title to be shown above your list of random posts.

Add block to widget

Once you have done that, switch to the ‘Posts’ tab in the column on the left.

From here, you can select the post type, post status, and order of the posts that you want to be displayed on your website.

Configure settings

Next, scroll down to the ‘Orderby’ dropdown menu and select the ‘Random’ option. If you don’t configure this setting, then the block will only display the most recent posts published on your site.

After that, you can also limit the posts to certain categories by selecting them in the ‘Limit to Category’ section.

Choose random order

You can also configure the settings for thumbnails, excerpts, custom CSS, and more by switching to other tabs in the block.

Finally, click the ‘Update’ button at the top to save your changes. Now, you can visit your website to check out the random posts displayed in the WordPress sidebar.

Preview for displaying random posts

Bonus: Optimize Your Blog Posts For SEO

Other than displaying random posts on your website, it is also important to optimize each and every post for SEO.

This will improve your website’s search engine rankings and bring more traffic, helping you generate leads.

To optimize your blog posts properly, we recommend using keyword research tools like the WPBeginner Keyword Generator. These tools will allow you to find relevant keywords to use in your content.

WPBeginner keyword generator tool for content updates

Other than that, you can also use SEO writing assistant tools like Semrush to discover LSI and related keywords, change the language tone, and find out the average article length.

You can also use All in One SEO to improve your content quality further. It is the best WordPress SEO plugin on the market that lets you add FAQs and comes with a headline analyzer, AI title generator, article schema, link assistant, and more.

AIOSEO's landing page

All of these features can ultimately help you boost the quality and SEO of your blog posts. For more details, you can see our complete AIOSEO review.

Some other tips to increase blog post ranking can be using categories and tags, improving readability, adding a meta description, or using visual content like videos and images in your posts.

To learn more, you can see our beginner’s guide on tips to optimize your blog posts.

We hope this article helped you learn how to display random posts in WordPress. You may also want to see our beginner’s guide on how to choose the best domain registrar for your website and our top picks for the best email marketing services for small businesses.

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.

The post How to Display Random Posts in WordPress (Easy Tutorial) first appeared on WPBeginner.

How to Optimize Your AdSense Revenue in WordPress

Are you looking to increase your Google AdSense revenue?

Google AdSense is a great way to make money online from your WordPress website. You can skyrocket your AdSense revenue by placing ads in high-converting areas, selecting the right theme, and choosing the best plugins.

In this article, we will share tips on how to optimize your AdSense revenue in WordPress.

Optimize your AdSense Revenue in WordPress

Here is a summary of all the topics we will cover in this post:

What Is AdSense and How Does it Work?

Google AdSense is an advertising network run by Google that allows bloggers and website owners to earn money by showing text, images, videos, and other interactive advertisements on their websites. These ads are targeted by site content and audience.

AdSense ads are cost-per-click (CPC), meaning you get paid every time an ad is clicked on your website. Showing these advertisements is a great way to make money online through your WordPress blog.

The amount you receive per click varies based on the ad content and user demographic. For example, traffic from tier-1 countries (US, UK, and Australia) usually gets a much higher CPC than tier-3 countries (Congo, Jamaica, and Sri Lanka).

Here are three factors that impact your overall AdSense revenue:

  • Ad size
  • Ad placement
  • Quality of traffic

Let’s take a look at which AdSense size and placements perform the best.

Best AdSense Ad Size and Placement

Google AdSense revenue depends on how your users interact with ads on your website. So, the strategic placement of ads is very important for increasing your AdSense revenue.

In our experience, the AdSense sizes that work best are:

  • 336 x 280 (Large Rectangle)
  • 300 x 250
  • 728 x 90
  • 160 x 600

Notice that these are fairly large ads and are more prominent by default. The areas where you would generally place them also have to be prominent.

The ideal ad placements are your site header, above the content, in-between content, and after-post content.

Sidebar ads rarely have a good click-through rate (CTR), so we tend to avoid them altogether.

The general rule of thumb is to place at least one ad unit above the fold of your WordPress website. Above the fold is the area users see when they land on your website without scrolling.

Placements of ads

When setting up Google AdSense, there are a few placement areas that you absolutely want to avoid at all costs because they can result in your account getting terminated:

  • Floating Scrolling Ads – Some publishers use floating sidebar widgets or floating footer bars to display ads that scroll with users. We’ve seen people getting their AdSense accounts banned for doing this, so we recommend against using this placement.
  • Popup Ads – We have also seen folks displaying their AdSense ads inside a lightbox popup. This is also against AdSense policies, and you should avoid this placement.
  • Ads above pagination – One of the best places to generate accidental clicks is above pagination. We have received a warning from Google in the past about this and made a quick change to prevent our account from being suspended.

Also, whatever you do, do not click on your own ads because that’s a surefire way to get your Google account banned.

Having that said, let’s take a look at the best Google AdSense plugins for WordPress that can help you increase your AdSense revenue.

Best Plugins for Managing and Inserting AdSense Ads in WordPress

The best way to manage ads in WordPress is by using an ad management plugin. These plugins allow you to insert and manage your ads from one spot without writing any code.

Additionally, many sites that use Google AdSense choose to use their ‘auto ads’ feature. This feature lets Google place the ads automatically on your site with no additional setup from you.

This works for some sites better than others, and if you don’t see the results you want from the auto ads, then here are some WordPress plugins to optimize your AdSense placements.

1. WPCode

WPCode - Best WordPress Code Snippets Plugin

WPCode is the best custom code snippets plugin for WordPress. With it, you can insert ad code anywhere you want on your website. You won’t need to edit any of your theme’s files, and you will have complete control of the placement.

All you have to do is take the ad code from Google, create a new snippet, and insert it into a post or page using a shortcode. You can also schedule ads to show for a specific period of time, such as a limited-time promotion.

In addition, you can use WPCode to track your ad performance on other popular platforms like Facebook, TikTok, or Pinterest. The WPCode Conversion Pixels addon lets you add tracking pixels so that you can track events like product page views, when users add items to their carts, as well as checkouts and purchases to help improve your ad-spend ROI.

The free WPCode plugin comes with everything you need to display ads on your site. To unlock scheduled snippets, conversion pixels, and other powerful features, you will need to upgrade to the premium version.

2. AdSanity

AdSanity WordPress plugin

AdSanity is a premium WordPress plugin that allows you to properly manage ads on your WordPress site.

It works with all advertising platforms, including Google AdSense. You can easily create and insert ads on your WordPress site and manage your ad units from your WordPress admin area.

You can create ad groups and display ads on a rotating basis. You can also display ads using drag-and-drop WordPress widgets.

For more information, you may want to take a look at our tutorial on how to manage ads in WordPress with AdSanity or how to insert ads within your post content.

3. Thrive Suite

Thrive Themes Suite

Thrive Suite is one of the best WordPress plugins to optimize your website or blog for AdSense revenue. It’s a one-stop marketing solution with the right tools to set up your site from scratch.

The Thrive Suite includes Thrive Theme Builder, Thrive Leads, Thrive Optimize, Thrive Automator, and more. You can design custom landing pages and also use the space on your homepage to display your ads.

Some of these tools are built for niche sites like online courses, quizzes, eCommerce shops, bloggers, and affiliate marketers. And all of these tools can help optimize any of your sites for AdSense ads.

Bonus: MonsterInsights

The MonsterInsights Google Analytics plugin

MonsterInsights is the best analytics solution for WordPress, and it helps you set up Google Analytics without editing code or hiring a developer.

With the MonsterInsights Ads addon, you can set up AdSense tracking on your WordPress website in just a few clicks and see how people are interacting with your ads.

You will get insights to increase your AdSense revenue and find out which ads get the most clicks. The plugin also helps find the best position for placing ads on your site and boosts the click-through rate (CTR).

Besides that, MonsterInsights helps set up advanced tracking like eCommerce tracking, conversion tracking, and more.

It also brings the most important analytics stats inside your WordPress dashboard so you can view how your site is performing at a glance and make data-driven decisions.

For more details, you can go through our detailed guide on how to track user engagement in WordPress with Google Analytics.

Best AdSense-Optimized Themes for WordPress

While you can add Google AdSense to any WordPress theme, there are some themes that are more optimized for advertisements.

These themes either have specially designated areas where you can place an ad code or a layout that allows you to insert ads in optimized locations.

Here are some AdSense-optimized WordPress themes that you can use.

1. Divi by Elegant Themes

Elegant Themes Divi

Divi by Elegant Themes is the best WordPress theme that’s optimized for Google AdSense. It offers thousands of page templates and customization options to place your AdSense ads.

The best thing about using Divi is that it offers a complete WordPress theme and visual page builder. You can customize and edit your theme by adding and removing elements using the drag and drop builder.

With Divi, you get hundreds of elements to add to your theme and over 2,200 page layouts. Besides that, there are multiple hover styles and effects, fonts and text styles, shape dividers, and more to customize your theme.

2. SeedProd

SeedProd Adsense Theme Template

SeedProd is the best WordPress theme and website builder. It comes with over 300 theme template kits, including a layout built specifically to place AdSense ads on your site.

The theme builder is easy to use for beginners with drag and drop functionality. You can fully customize the position of your ads and also change the size.

Moreover, it has many other features that could help optimize your website. SeedProd also integrates with popular email marketing services that can let you build an email list to retain your website traffic.

3. Ad-Sense

Ad-Sense theme

Ad-Sense is a theme that’s designed and optimized for Google AdSense. It is one of the most ad-friendly themes on the market.

With Ad-Sense, you get different features like ad placement to put your ads in the navigation menu, header, site background, before and after content, and more.

The theme also lets you manage your ads, automatically detects ad blockers, and locks content for ad-block users. There are different predefined layouts to choose from, and you can customize them according to your needs.

4. MH Newsdesk

MH Newsdesk theme

MH Newsdesk is a fully mobile-friendly WordPress theme for magazines and news websites.

The main feature of MH Newsdesk is that it is a fully AdSense-optimized theme for WordPress. The theme comes with widget-ready areas, allowing you to place your ad widgets anywhere on your site.

The theme is SEO-optimized, and you won’t have to worry about slow performance. It also comes with Google fonts, so you can easily change the font of your text and headings.

5. ProMax

Promax theme

ProMax is a beautifully designed free AdSense-ready theme for WordPress.

It comes with plenty of spots to prominently display your Adsense ads above the fold area without compromising user experience.

The theme features a custom background, header, and social menu. Plus, you can easily customize any element in the theme to match your business needs.

6. News Portal

News Portal

News Portal is an excellent free WordPress theme for news, magazine, and blogging sites.

It comes with built-in space for AdSense ads in the top header area. This will display your ad on all pages and posts.

The theme has multiple color schemes that give you the choice to change the look of your website. It also provides different layout designs and custom widgets for additional customization.

7. Public Opinion

Public Opinion

Public Opinion is a premium WordPress magazine theme. It comes with a white background that highlights your content and your colorful AdSense ads.

The theme has a featured section to share your top articles on the homepage. It uses beautiful font styles and font types for the navigation menu, headers, text, and content.

Public Opinion is fully customizable using page builders like Elementor Pro. This page builder integration comes with custom blocks for images, videos, sections, buttons, and more.

Bonus: Ask Users to Disable Adblockers

Now that you understand how to optimize your WordPress site for AdSense ads, the only hurdle is adblockers.

What Is an Adblocker?

As the name suggests, an adblocker blocks ads for users so that they don’t see them when visiting your website. There are several browser addons and mobile apps that, when enabled, will detect and disable AdSense ads on websites and apps.

You may wonder why your ads are not creating your expected revenue. And the simple answer is that your site visitors have an adblocker enabled.

How to Disable Adblockers in WordPress

You can nicely ask your users to disable their adblockers by showing a modal popup with a custom message.

While this may not guarantee a quick boost in your AdSense revenue, it’s a step to ensure you are doing something about the adblockers.

The AdSanity plugin comes with an Ad Block Detection add-on. It lets you add and display a custom warning to users where you can ask them to disable their adblockers and continue to read your content.

Edit AdSanity ad blocker settings

We recommend you check out our complete guide on how to detect Adblock users in WordPress. It talks about different methods to get the adblockers disabled so that you can continue to make money online.

We hope this article helped you learn how to optimize your AdSense revenue in WordPress and boost your earnings. You can also check out our other WordPress guides that can further help you grow your site.

Best WordPress Guides for Growing Your AdSense Site

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.

The post How to Optimize Your AdSense Revenue in WordPress first appeared on WPBeginner.

How to Replace Default Theme and Plugin Editor in WordPress

Are you looking for a way to replace the default theme and plugin editor in WordPress?

The default WordPress theme and plugin editors are plain text editors with limited functionality. By replacing these editors with better tools, you can use advanced features like access control, child theme creation, file downloads, and more.

In this article, we will show you how to easily replace the default theme and plugin editor in WordPress.

Replacing the default theme and plugin editor in WordPress

Why Replace the Default Theme and Plugin Editor in WordPress?

The default theme editor in the dashboard of your WordPress website allows you to make direct changes to the code in your theme files.

Similarly, the plugin editor lets you edit the code of the installed plugins on your website.

Default theme editor preview

These built-in editors have text editor interfaces that lack advanced features like access control, file download/upload, and child theme creation. This makes it time-consuming for you to add and maintain custom code.

Plus, if an unauthorized person gains access to your WordPress admin area, then they can easily access the default editors to edit your theme and plugin files. This can allow them to install malware on your website.

By replacing these editors with a plugin, you can easily customize your WordPress themes and plugins from the dashboard by adding or removing code snippets, customizing colors, modifying various template files, CSS styles, and more.

This will allow you to make quick changes to your theme or plugin without accessing your website files via FTP.

You can also create child themes, control editor access to make your website more secure, and even upload files to your plugins and themes from your computer.

Having said that, let’s see how to easily replace the default theme and plugin editor in WordPress. You can use the quick links below to jump to the different parts of our tutorial:

How to Replace the Default Theme and Plugin Editors in WordPress

First, you need to install and activate the Theme Editor plugin. For detailed instructions, you can see our beginner’s guide on how to install a WordPress plugin.

Note: Before making any changes to your theme or plugin files, please make sure to create a complete backup of your WordPress website. This will come in handy if anything goes wrong and you have to restore WordPress from a backup.

Upon activation, you need to head over to the Theme Editor » Settings page from the WordPress admin sidebar.

Once you are there, check the ‘Yes’ box for the ‘Enable code editor for theme’ option.

After that, if you want to disable the default WordPress theme editor, then you need to check the ‘Yes’ box next to the ‘Disable WordPress theme file editor?’ option.

Configure theme editor settings

Once you have done that, just switch to the ‘Plugin Editor’ tab at the top.

Here, you need to check the ‘Yes’ box next to the ‘Enable code editor for plugin’ option.

You can also disable the default editor by choosing the ‘Yes’ option for the ‘Disable WordPress plugin file editor?’ setting.

Configure plugin editor settings

Next, switch to the ‘Code Editor’ tab from the top of the page.

From here, you can choose a theme for the code editor from the dropdown menu. This will display the code in your theme and plugins in different backgrounds and font colors.

Once you are done, don’t forget to click the ‘Save Changes’ button to store your settings.

Choose a code editor theme

Editing Your Theme Files Using the Theme Editor

Now, you need to visit the Theme Editor » Theme Code Editor page from the WordPress admin dashboard.

Once you are there, you need to select the theme that you want to edit from the dropdown menu in the right corner of the screen. Next, you must choose the theme file where you want to add code from the sidebar on the right.

After that, you can easily add, remove, or edit code to your theme files from the theme editor on your screen.

Choose theme to edit

Once you are done, don’t forget to click the ‘Update File’ button to store your settings.

You can also download the file you just edited by clicking on the ‘Download File’ button. If you want to download the whole theme instead, then you can click the ‘Download Theme’ button.

Save theme files

Editing Your Plugins Using the Plugin Editor

If you want to add code to your plugin files instead, then you need to visit the Theme Editor » Plugin Code Editor page from the WordPress admin sidebar.

Once you are there, choose a plugin to edit from the dropdown menu in the right corner of the screen.

After that, you can select a plugin file to edit from the sidebar on the right and then edit it using the plugin code editor.

Edit plugin files

Once you are satisfied with your changes, just click the ‘Update File’ button to store your settings.

You can even download the file you just edited by clicking the ‘Download File’ button.

If you want to download the plugin with all the changes that you have made, then you can click the ‘Download Plugin’ button instead.

Download plugin files

Configuring Access Control With the Theme Editor Plugin

The Theme Editor plugin even lets you control access to your theme and plugin editors in WordPress. However, this feature is only available in the pro version of the plugin.

This way, only users who you approve will be able to edit the themes and plugins on your website.

By using access control, you make your website more secure by allowing only trustworthy users to make changes to your files, reducing the risk of malware.

First, you need to visit the Theme Editor » Access Control page from the WordPress dashboard.

Control the access to theme and plugin editor

From here, you just need to check the options in the columns that you want the WordPress user roles to have access to.

For example, if you want the editor to have the ability to update theme files, then you need to check that box in the ‘Editor’ row.

Once you are done, simply click the ‘Save Changes’ button to store your settings.

Creating a Child Theme With the Theme Editor

If you want to create a child theme to customize your WordPress themes, then you can visit the Theme Editor » Child Theme page from the WordPress admin sidebar.

Once you are there, you will first need to choose a parent theme from the dropdown menu in the middle and then click the ‘Analyze’ button.

Choose a parent theme

Once that’s done, you must provide a name for your new theme directory and select where to save your child theme stylesheet.

After that, you can even provide a name, description, author, and version for the child theme that you are creating.

Once you are done, just click the ‘Create New Child Theme’ button.

Configure child theme settings

Now that you have created a child theme, you can edit the selector, web fonts, CSS, child style, and theme files from the menu bar at the top of the page.

The changes that you make will automatically be saved in your child theme.

Child theme created

Bonus: Use WPCode to Add Custom Code to Your Website

Adding code to your website using plugins or theme file editors is always a bit risky because the smallest error can break your WordPress website and make it inaccessible.

That is why we recommend using the free WPCode plugin instead to add custom code to your website. It is the best WordPress code snippets plugin on the market.

First, you need to install and activate the WPCode plugin. For detailed instructions, you can see our tutorial on how to install a WordPress plugin.

Upon activation, you need to head over to the Code Snippets » + Add Snippet page from the WordPress admin sidebar.

From here, you can use the WPCode snippet library to add pre-made code snippets to your WordPress site.

However, if you want to add custom code, then you can also do that by clicking the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will open the ‘Create Custom Snippet’ page, where you can start by adding a title for your code snippet.

After that, you need to select a code type from the dropdown menu in the right corner of the screen. For example, if you want to add PHP code, then you just need to select the ‘PHP Snippet’ option.

Next, simply add your custom code into the ‘Code Preview’ box.

PHP Snippet as code type

Once you have done that, scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

Your custom code will be automatically executed on your site upon activation.

Choose an insertion method

Finally, scroll back to the top and toggle the ‘Inactive’ switch to ‘Active’.

After that, click the ‘Save Snippet’ button to save and execute the custom code on your website.

Save code snippet

For more details, you can see our guide on how to add custom code in WordPress.

We hope this article helped you learn how to easily replace the default theme and plugin editor in WordPress. You may also want to see our beginner’s guide on how to safely update WordPress and our expert picks for the must-have WordPress plugins to grow your site.

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.

The post How to Replace Default Theme and Plugin Editor in WordPress first appeared on WPBeginner.

How to Display Ads Only to Search Engine Visitors in WordPress

Do you want to show targeted ads to only visitors from search engines?

From our experience and the research of many industry experts, it seems that search engine visitors are more likely than your regular readers to click on targeted advertisements. By showing ads only to these visitors, you can boost the click-through rate (CTR) and increase sales.

In this article, we will show you how to display ads only to search engine visitors in WordPress.

How to display ads only to search engine visitors in WordPress

Why Show Display Ads to Only Search Engine Visitors?

There are different ways to make money online, and showing display ads is one of them.

You can use Google AdSense to show ads on your WordPress blog and earn a set fee when a user clicks on the advertisements. This strategy is called cost-per-click (CPC).

However, getting more clicks can be a challenge if the ads aren’t targeted to the right audience. This is where limiting display ads to search engine visitors can help boost ad revenue.

Different studies, industry experts, and our own experience shows that visitors from search engines are more likely to click on ads on your site compared to other visitors. You can show the right ads to the right users and improve CPC.

This strategy also helps show ads only when they are needed. Having too many advertisements can be distracting and bad for the user experience. By displaying them to only search engine visitors, your WordPress website won’t be cluttered with ads.

That said, let’s see how you can display ads to only search engine visitors.

Showing Display Ads to Only Search Engine Visitors

To display ads to only visitors from search engines, you will need to add a custom code snippet to your WordPress website.

This might sound technical and difficult, but we will show you an easy way to add code snippets without editing code or hiring a developer.

If you haven’t set up ads on your site, then please see our guide on how to properly add Google AdSense to WordPress.

Next, you will need to install and activate the WPCode plugin. To learn more, please see our guide on how to install a WordPress plugin.

WPCode is the best code snippet plugin for WordPress, and it helps you insert custom code anywhere on your site. It also helps you manage and organize all your code snippets.

Note: For this tutorial, we will use the WPCode Lite version, which is available for free. However, there are premium plans that offer more features like conditional logic, safe error handling, a code snippets library, and more.

Upon activation, you need to head to Code Snippets » + Add Snippet from your WordPress dashboard. Next, click the ‘Add Your Custom Code (New Snippet)’ option.

Add custom CSS snippet

From here, you will need to copy this code snippet:

$ref = $_SERVER['HTTP_REFERER'];
$SE = array('/search?', 'images.google.', 'web.info.com', 'search.', 'del.icio.us/search', 'soso.com', '/search/', '.yahoo.');
foreach ($SE as $source) {
  if (strpos($ref,$source)!==false) {
    setcookie("sevisitor", 1, time()+3600, "/", ".wpbeginner.com"); 
    $sevisitor=true;
  }
}
  
function wpbeginner_from_searchengine(){
  global $sevisitor;
  if ($sevisitor==true || $_COOKIE["sevisitor"]==1) {
    return true;
  }
  return false;
}

Note: In the setcookie line, be sure to change .wpbeginner.com to your own site domain.

Next, you must paste the code into the WPCode ‘Code Preview’ area. You will also need to enter a name for your snippet and then click the ‘Code Type’ dropdown menu and select the ‘PHP Snippet’ option.

Enter custom code for search engine visitors

After that, you will need to scroll down and select the Insertion method for the code snippet.

WPCode will use the ‘Auto Insert’ option by default and run the code everywhere. However, you can change this and insert the custom code on specific pages, before or after content, show it on eCommerce pages, and more.

Edit insertion method for code

As an alternative, you can also switch to the ‘Shortcode’ insertion method and manually enter a shortcode to run the code snippet.

For this code snippet, we recommend using the Auto Insert method.

Once you are done, don’t forget to click the toggle at the top to activate the code snippet, and then click the ‘Save Snippet’ button.

Activate and save ad code in WPCode plugin

Choose Where to Display Ads on Your Site

Next, you will need to add another code snippet and choose where you’d like to display the ads to only search engine users.

Simply copy the following code:

<?php if (function_exists('wpbeginner_from_searchengine')) {
  if (wpbeginner_from_searchengine()) { ?>
    INSERT YOUR CODE HERE
<?php } } ?>

Note: Don’t forget to replace ‘INSERT YOUR CODE HERE’ in the above snippet with your Google AdSense code.

The snippet above uses the first code as a reference and analyzes whether the referrer agent is from any type of search URL, which includes Google, Yahoo, Delicious, and more.

If a visitor’s browser says that the referrer agent is from any search site that you have specified, then it will store a cookie on their browser called ‘visitor’ for 1 hour from the time they visited your site.

To add the code, simply go to Code Snippets » + Add Snippet from your WordPress dashboard and select the ‘Add Your Custom Code (New Snippet)’ option.

Add custom CSS snippet

Next, you can enter a name for your code snippet at the top and paste the code into the ‘Code Preview’ area.

You will also need to change the ‘Code Type’ by clicking the dropdown menu and selecting the ‘PHP Snippet’ option.

Enter code and select code type

After that, you can click the ‘Save Snippet’ button and scroll down to the Insertion section.

Here, you will need to select the ‘Shortcode’ method. This way, you can easily add the shortcode to show display ads anywhere on your site.

Add shortcode for display ads

You can copy the shortcode or write it down in a notepad file.

When you are done, don’t forget to click the toggle at the top to activate the code and then click the ‘Update’ button.

To add the shortcode, you can head to any section of your website. For example, if you want to show banner ads to search engine users in the sidebar, then just go to Appearance » Widgets from the WordPress dashboard.

From here, you can click the ‘+’ button to add a Shortcode widget block to the sidebar area.

Add a shortcode widget block

Go ahead and enter the shortcode you just copied. Once you are done, simply click the ‘Update’ button.

WordPress will now display the search engine-specific ads that you have chosen to these users for a total of one hour from the time they first visited your site.

If this user bookmarks your site and comes back to it one day later because they like your content, then they will be considered your regular reader and will not see the search engine-specific ads.

We hope this article helped you learn how to display ads only to search engine visitors in WordPress. You may also want to see our ultimate guide to WordPress SEO and our expert picks for the best WordPress ad management plugins.

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.

The post How to Display Ads Only to Search Engine Visitors in WordPress first appeared on WPBeginner.

How to Display Ad Blocks in Specific Posts in WordPress

Do you want to display ad blocks in specific posts on your WordPress website?

Inserting ad blocks into a specific post allows you to showcase ads where your users will be highly engaged with the content. This increases ad visibility and helps you get more clicks.

In this article, we will show you how to easily display ad blocks in specific WordPress posts.

Displaying Ad blocks in specific posts in WordPress

Why Display Ads in Specific WordPress Posts?

When visiting a WordPress website, you will often see banner ads in the sidebar or beneath the header. Since those are very common ad spots, they can lead to banner blindness, where users won’t notice the ads. In turn, this can affect the click rate.

By displaying ad blocks in specific WordPress posts, you can increase the visibility of your ads and target users who are most engaged with your content.

Not only does this help prevent ad fatigue by spreading out ads across multiple pages on your WordPress blog, but it also allows you to segment your audience. By showing targeted ads to users who are more likely to be interested in them, you improve your chances of engagement and clicks.

For example, a user who is reading one of your travel blog posts is more likely to be interested in an ad for travel gear or flights and may click on it to check out the prices.

Having said that, let’s see how to easily display ads in specific WordPress posts. You can use the quick links below to jump to the method you wish to use:

Method 1: Display Ad Blocks in Specific WordPress Posts Using WPCode (Recommended)

The easiest way to display ad blocks in specific WordPress posts is by using the WPCode plugin.

It is the best WordPress code snippets plugin on the market that makes it super easy to place ads within any page, post, or widget area on your WordPress website.

With WPCode, you can show advertisements from third-party platforms like Google AdSense or your own hosted ads.

First, you will need to install and activate the WPCode plugin. For more detailed instructions, please see our beginners’ guide on how to install a WordPress plugin.

Note: You can also use the free WPCode plugin for this tutorial. However, upgrading to the Pro version will give you access to a cloud library of code snippets, smart conditional logic, and more.

Upon activation, head over to the Code Snippets » + Add Snippet page in the WordPress admin sidebar.

From here, you need to click on the ‘Use Snippet’ button under the ‘Add Your Custom Code (New Snippet)’ option.

Add new snippet

This will take you to the ‘Create Custom Snippet’ page, where you can start by typing a name for your code snippet. The code snippet title is only for your reference and won’t be shown to users on the website’s front end.

After that, you need to select ‘HTML Snippet’ as the Code Type from the right dropdown menu.

Choose HTML Snippet as code type for displaying ad blocks

Next, you need to choose the type of ad you want to place on your site.

If you are using the ad code provided by Google AdSense, then you may want to see our guide on how to optimize your AdSense revenue in WordPress.

However, if you are creating your own ad, then you will need to get the code from the person who is paying you to show the ad on your site or write your own code.

Upon getting your ad code, simply copy and paste it into the ‘Code Preview’ box.

Copy and paste ad code into Code Preview box

Once you have done that, you must scroll down to the ‘Insertion’ section and choose the ‘Auto Insert’ mode.

The ad will automatically be displayed in the specific post you choose.

Choose an insertion method

Next, click on the ‘Location’ dropdown menu to expand it, and then select the ‘Page-Specific’ tab from the left sidebar.

From here, choose the ‘Insert After Paragraph’ option.

You can also modify the number of paragraphs after which you want to insert the snippet.

For example, if you want to display the ad block after the 3rd paragraph, then you can type this value into the ‘after paragraph number’ box.

Choose Insert After Paragraph as the snippet location

Next, scroll down to the ‘Smart Conditional Logic’ section and toggle the ‘Enable Logic’ switch to Active.

After that, make sure that the ‘Show’ option is selected for the code snippet condition. Once you have done that, just click the ‘+ Add new group’ button.

Toggle the Conditional Logic switch to active

This will open up some new settings in the ‘Smart Conditional Logic’ section.

From here, you need to select the ‘Page URL’ option from the dropdown menu on the left.

Choose the Page URL option from the dropdown menu on the left

After that, you must select the ‘Is’ option from the dropdown menu in the middle.

Next, add the URL of the specific post where you want to display the ad block into the empty field in the right corner of the screen.

If you want to display this ad on more than one page or post, just click ‘AND’ and then follow the same process to insert the other post URL.

Once you have created this conditional logic, your ad block will only be displayed in that specific WordPress post.

Add the specific post URL

Now, scroll back to the top and toggle the ‘Inactive’ switch to ‘Active’.

Finally, click the ‘Save Snippet’ button to execute the ad code on your website automatically.

Save the snippet for ad blocks

Now, you can visit the specific post you chose to see the ad block in action.

This is what it looked like on our demo website.

WPCode Ad Preview

Method 2: Display Ad Blocks in WordPress Posts Using AdSanity

If you don’t want to use code on your website, then this method is for you.

AdSanity is a premium WordPress ad management plugin that allows you to easily create ad blocks and display them anywhere on your WordPress site. It works with any third-party ad network, including Google AdSense.

First, you need to install and activate the AdSanity plugin. For more details, please see our step-by-step guide on how to install a WordPress plugin.

Upon activation, you need to head to the Adsanity » Create Ad page from the WordPress admin sidebar.

From here, you can start by typing a name for the ad that you are creating.

Next, you must switch to the ‘Ad Hosted On-Site’ tab at the top if you are creating your own hosted ad.

Type Ad name

However, if you are displaying an ad from a third-party platform, then go to the ‘External Ad Network’ tab. Similarly, if you want to upload an HTML file for your ad, then you must switch to the ‘HTML5’ tab.

For this tutorial, we will be displaying a self-hosted ad in a specific WordPress post, but the steps will be the same for other types of ads.

Once you have entered a name for your ad, select its size from the dropdown menu. This will be the banner size of the ad in your post.

Choose an Ad size

After that, you need to scroll down to the ‘Ad Details’ section and copy and paste the tracking URL of the ad you want to display.

Once you have done that, check the ‘Open in a new window?’ option if you want the ad to open up in a different window when a user clicks on it.

You can also set an image for your ad by clicking on the ‘Set ad image’ link. This will open up the WordPress media library, where you can upload an image.

Paste the tracking URL for the Ad and set an image

Finally, click the ‘Publish’ button at the top to save your changes.

You can also click on the ‘Edit’ link in the ‘Publish’ section to set a start date and an expiration date for the ad.

Once you have clicked on the ‘Publish’ button, you can display the ad block on any page or post on your WordPress website.

Set an Ad schedule

Display the Ad in a Specific WordPress Post

First, you will need to open an existing or new WordPress post where you want to display the ad you created.

Once you are there, click the ‘+’ button in the top left corner of the screen to open up the block menu. Next, you need to look for and add the AdSanity Single Ad block to the WordPress post.

Add the AdSanity Single Ad block

After that, select the ad that you want to display from the dropdown menu in the block.

You can also choose an alignment option for the ad block.

Choose Ad from dropdown menu

Finally, click the ‘Update’ or ‘Publish’ button at the top to save your changes.

Now, you can visit your website to check out the ad block in action.

Ad Preview

We hope this article helped you learn how to display ad blocks in specific WordPress posts. You may also want to see our tutorial on how to sell ads on your WordPress blog and our expert picks for the best affiliate marketing tool and plugins for WordPress to make money online.

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.

The post How to Display Ad Blocks in Specific Posts in WordPress first appeared on WPBeginner.