How to Limit the Number of Archive Months Displayed in WordPress

Do you want to display the number of archive months displayed in WordPress? If you have been blogging for years, you will notice that your archives list will become too long. In this article, we will show you how to limit the number of archive… Read More »

The post How to Limit the Number of Archive Months Displayed in WordPress appeared first on WPBeginner.

Do you want to display the number of archive months displayed in WordPress? If you have been blogging for years, you will notice that your archives list will become too long. In this article, we will show you how to limit the number of archive months displayed in WordPress.

How to limit number of archive months in WordPress

Method 1. Limit Number of Archive Months with Plugin

This method is easier and it is recommended for all users.

First thing you need to do is install and activate the Collapsing Archives plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Appearance » Widgets page and add the Collapsing Archives widget to your sidebar.

Collapse archives

The widget menu will expand to show its settings.

The Collapsing Archives widget uses JavaScript to collapse your archive links into collapsible yearly links. Your users can click on years to expand them to view monthly archives. You can even make monthly archives collapsible and allow users to see post titles underneath.

Review the widget settings to suit your needs and then click on the Save button to store your settings.

You can now visit your website to see the widget in action.

Collapsing archives

Method 2. Replace Default Archives with Compact Archives

This method provides a cleaner alternative to the default archives widget by beautifully displaying them in a compact more presentable way.

First, you need to install and activate the Compact Archives plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Appearance » Widgets page and add the ‘Compact Archives’ widget to your sidebar.

Compact Archives settings

Compact Archives plugin comes in three styles. You can choose from block, initials, or numeric.

Don’t forget to click on the save button to store your widget settings.

You can now visit your website to see the compact archives in action.

Compact Archives preview

You can also use Compact Archives plugin to create a custom archives page on your site. For more details see our guide on how to create compact archives in WordPress

Method 3. Manually Limit Number of Archive Months in WordPress

This method requires you to add code to your WordPress theme files. If you haven’t done this before, then take a look at our guide on how to copy and paste code in WordPress.

You will need to add the following code to your theme’s functions.php file or a site-specific plugin.


// Function to get archives list with limited months
function wpb_limit_archives() { 

$my_archives = wp_get_archives(array(
	'type'=>'monthly', 
	'limit'=>6,
	'echo'=>0
));
	
return $my_archives; 

} 

// Create a shortcode
add_shortcode('wpb_custom_archives', 'wpb_limit_archives'); 

// Enable shortcode execution in text widget
add_filter('widget_text', 'do_shortcode'); 

This code fetches the archives list and limits it to past 6 months only. It then creates a shortcode and enables shortcode in text widgets.

You can now go to Appearance » Widgets page and add a ‘Text’ widget to your sidebar. Switch to the text mode and add your shortcode like this:

<ul>
[wpb_custom_archives]
</ul>

Don’t forget to save your widget settings.

You can now visit your website to see your custom archives list in action.

That’s all, we hope this article helped you learn how to limit the number of archive months displayed in WordPress. You may also want to see our list of these most useful tricks for the WordPress functions file.

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 the Number of Archive Months Displayed in WordPress appeared first on WPBeginner.

How to Display Recent Posts From A Specific Category In WordPress

Do you want to display recent posts from a specific category in WordPress? The default recent posts widget shows posts from all categories, and there is no option to filter them by category. In this article, we will show you how to easily display recent… Read More »

The post How to Display Recent Posts From A Specific Category In WordPress appeared first on WPBeginner.

Do you want to display recent posts from a specific category in WordPress? The default recent posts widget shows posts from all categories, and there is no option to filter them by category. In this article, we will show you how to easily display recent posts from a specific category in WordPress.

Display recent posts from specific category in WordPress

Filtering Posts by Category in WordPress

If you just want to create a page to display recent posts from a particular category, then your WordPress site already has separate pages for each category.

You can add links to all your category pages by visiting Appearance » Widgets page and adding the ‘Categories’ widget to your sidebar. You can also add categories in your navigation menus.

On the other hand, if you want to show recent posts from a specific category in your sidebar, then there is no default widget for that. The default recent posts widget does not allow you to filter posts by category or tags.

Thankfully there is another way. Let’s take a look at how to easily display recent posts from specific category in WordPress.

Method 1. Show Recent Posts from a Category Using Plugin

This method is easier, and it is recommended for most users.

First thing you need to do is install and activate the Recent Posts Widget Extended plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit the Appearance » Widgets page and add ‘Recent Posts Extended’ widget to your sidebar.

Limit recent posts by category

The widget menu will expand to show its settings. You need to select the category or categories that you want to display under the ‘Limit to Category’ option.

The widget comes with a lot of options that you can customize. You can show post thumbnail, date, relative date, post summary / excerpts, and more.

Don’t forget to click on the save button to store your widget settings.

You can now visit your website to see the recent posts displayed by category.

Recent posts from specific category

Display Recent Posts by Category Using Shortcode

The Recent Posts Extended Widget also allows you to use shortcode to display recent posts anywhere on your site including posts and pages.

You will need to edit the post or page where you want to display the recent posts from a specific category. In the post editor, you will need to add the following shortcode:

[rpwe limit="5" excerpt="true" cat="72" ]

This shortcode displays 5 recent posts from a specific category with the post excerpt. You will need to replace the cat value with the ID of the category that you want to display. See our article on how to find category ID in WordPress.

After adding the shortcode, you can save your post or page to view your changes.

Posts by category displayed using shortcode

Method 2. Display Recent Posts From Specific Category using Code Snippet

This method requires you to add code to your WordPress theme files. If you haven’t done this before, then take a look at our guide on how to copy and paste code in WordPress.

You will need to add the following code in your WordPress theme files where you want to display recent posts from a specific category.

<?php $catquery = new WP_Query( 'cat=72&posts_per_page=5' ); ?>
<ul>

<?php while($catquery->have_posts()) : $catquery->the_post(); ?>

<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile;
	wp_reset_postdata();
?>

The first line of this code creates a new WordPress query with a specific category ID. You need to replace it with your own category ID. It only shows post title in a list.

You can change it to display full content by adding the following code:

<?php $catquery = new WP_Query( 'cat=72&posts_per_page=5' ); ?>
<ul>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
<ul><li><?php the_content(); ?></li>
</ul>
</li>
<?php endwhile; ?> 
</ul>
<?php wp_reset_postdata(); ?>

You can also replace the the_content with the_excerpt to display post excerpts instead of full article.

We hope this article showed you how to easily display recent posts from a specific category in WordPress. You may also want to see our list of most wanted category hacks and 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 Display Recent Posts From A Specific Category In WordPress appeared first on WPBeginner.

How to Display Recent Posts From A Specific Category In WordPress

Do you want to display recent posts from a specific category in WordPress? The default recent posts widget shows posts from all categories, and there is no option to filter them by category. In this article, we will show you how to easily display recent… Read More »

The post How to Display Recent Posts From A Specific Category In WordPress appeared first on WPBeginner.

Do you want to display recent posts from a specific category in WordPress? The default recent posts widget shows posts from all categories, and there is no option to filter them by category. In this article, we will show you how to easily display recent posts from a specific category in WordPress.

Display recent posts from specific category in WordPress

Filtering Posts by Category in WordPress

If you just want to create a page to display recent posts from a particular category, then your WordPress site already has separate pages for each category.

You can add links to all your category pages by visiting Appearance » Widgets page and adding the ‘Categories’ widget to your sidebar. You can also add categories in your navigation menus.

On the other hand, if you want to show recent posts from a specific category in your sidebar, then there is no default widget for that. The default recent posts widget does not allow you to filter posts by category or tags.

Thankfully there is another way. Let’s take a look at how to easily display recent posts from specific category in WordPress.

Method 1. Show Recent Posts from a Category Using Plugin

This method is easier, and it is recommended for most users.

First thing you need to do is install and activate the Recent Posts Widget Extended plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit the Appearance » Widgets page and add ‘Recent Posts Extended’ widget to your sidebar.

Limit recent posts by category

The widget menu will expand to show its settings. You need to select the category or categories that you want to display under the ‘Limit to Category’ option.

The widget comes with a lot of options that you can customize. You can show post thumbnail, date, relative date, post summary / excerpts, and more.

Don’t forget to click on the save button to store your widget settings.

You can now visit your website to see the recent posts displayed by category.

Recent posts from specific category

Display Recent Posts by Category Using Shortcode

The Recent Posts Extended Widget also allows you to use shortcode to display recent posts anywhere on your site including posts and pages.

You will need to edit the post or page where you want to display the recent posts from a specific category. In the post editor, you will need to add the following shortcode:

[rpwe limit="5" excerpt="true" cat="72" ]

This shortcode displays 5 recent posts from a specific category with the post excerpt. You will need to replace the cat value with the ID of the category that you want to display. See our article on how to find category ID in WordPress.

After adding the shortcode, you can save your post or page to view your changes.

Posts by category displayed using shortcode

Method 2. Display Recent Posts From Specific Category using Code Snippet

This method requires you to add code to your WordPress theme files. If you haven’t done this before, then take a look at our guide on how to copy and paste code in WordPress.

You will need to add the following code in your WordPress theme files where you want to display recent posts from a specific category.

<?php $catquery = new WP_Query( 'cat=72&posts_per_page=5' ); ?>
<ul>

<?php while($catquery->have_posts()) : $catquery->the_post(); ?>

<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile;
	wp_reset_postdata();
?>

The first line of this code creates a new WordPress query with a specific category ID. You need to replace it with your own category ID. It only shows post title in a list.

You can change it to display full content by adding the following code:

<?php $catquery = new WP_Query( 'cat=72&posts_per_page=5' ); ?>
<ul>
<?php while($catquery->have_posts()) : $catquery->the_post(); ?>
<li><h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>
<ul><li><?php the_content(); ?></li>
</ul>
</li>
<?php endwhile; ?> 
</ul>
<?php wp_reset_postdata(); ?>

You can also replace the the_content with the_excerpt to display post excerpts instead of full article.

We hope this article showed you how to easily display recent posts from a specific category in WordPress. You may also want to see our list of most wanted category hacks and 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 Display Recent Posts From A Specific Category In WordPress appeared first on WPBeginner.

How to Install and Setup WordPress Multisite Network

Do you want to setup a WordPress multisite network? WordPress comes with a built-in capability to create multiple websites using the same WordPress install. In this article, we will show you how to install and setup a WordPress multisite network. Since this is a comprehensive… Read More »

The post How to Install and Setup WordPress Multisite Network appeared first on WPBeginner.

Do you want to setup a WordPress multisite network? WordPress comes with a built-in capability to create multiple websites using the same WordPress install. In this article, we will show you how to install and setup a WordPress multisite network.

How to install and setup WordPress multisite network

Since this is a comprehensive article, we have added the table of contents for easier navigation:

What is WordPress Multisite?

A WordPress multisite network allows you to run and manage multiple WordPress sites from a single WordPress installation.

You can create new sites instantly and manage them using the same username and password. You can even allow other users to signup and create their own blogs on your domain.

Pros of Using a WordPress Multisite Network

In many situations, a WordPress multisite network can be more useful than managing multiple standalone WordPress sites. Here are some of the advantages of using a WordPress multisite network:

  1. As the network administrator, you can easily manage multiple sites from a single dashboard.
  2. Each site on the network can have its own admins. The site admins will have the capabilities to manage only their own website.
  3. You can install plugins and themes and activate them for multiple sites with one download.
  4. Multisite network also makes it easier for you to manage updates. You only need to update your WordPress, plugins, or themes on one “master” install.

Cons of Using a WordPress Multisite Network

Creating a WordPress multisite network is not always as helpful in managing multiple sites. Here are some of the disadvantages of using a multisite network that you should keep in mind.

  1. All sites on the network share the same resources. This means that when your site is down, all other sites on the network go down as well.
  2. Managing server resources in case of unexpected traffic can be difficult for a beginner level user.
  3. If your website gets hacked, then this means all sites on your network will get hacked.
  4. Some WordPress plugins may not work well on a multisite network.

Who Needs a WordPress Multisite Network?

Just because you manage multiple WordPress websites does not mean you need to start using a multisite network.

There are third party tools like ManageWP or InfiniteWP that you can use to manage all your WordPress sites under one roof.

Here are some example scenarios when creating a multisite network makes sense:

  • A magazine website with different sections managed by different teams.
  • A business website with sub-sites for different locations and branches.
  • Government or non-profit websites can use WordPress multisite for different departments, locations, and regions.
  • Your own network of blogs running on multiple subdomains.
  • Schools and colleges allowing students to create their own blogs on school servers.

Requirements for a WordPress Multisite Network

All websites on a WordPress multisite network share the same server resources. This means that the most important thing you will need is a good WordPress hosting.

If you are planning on having just a couple of websites with low traffic, then you can probably get away with shared hosting.

However, due to the nature of multi-sites, you’d need VPS hosting or a dedicated server as your sites grow.

We recommend Bluehost because they offer both shared hosting and VPS/Dedicated servers, and they are also one of the official WordPress hosting partners.

We’ve also worked with SiteGround and InMotion Hosting, and they also provide excellent service.

Apart from web hosting, you will need some basic knowledge of installing WordPress and editing files using FTP.

Choosing a Domain Structure for Your Multisite Network

On a WordPress multisite network, you can add new sites using either subdomains or sub-directories.

http://site1.example.com
http://example.com/site1/

If you choose subdomains, then you will have to configure wildcard subdomains on your server (we will show you how to do that later in this article).

On the other hand, if you choose sub-directories or path based URLs for sites on your network, then the only thing you need to do is enable pretty permalinks on your root site.

Setting Up Wildcard Subdomains

If you decide to use subdomains for websites on your multisite network, then you will need to setup wildcard subdomains for your multisite network.

To do that, first you need to login to your WordPress hosting account’s cPanel dashboard. Scroll down to the Domains section and then click on Subdomains.

Subdomains in cPanel dashboard

Note: Depending on your web hosting service, your cPanel dashboard may look slightly different than the screenshot above. This screenshot is from the cPanel on Bluehost.

On the next screen, you need to enter the * sign in the subdomain field and select your main domain from the drop down menu.

Adding wildcard subdomain

Cpanel will automatically detect the document root and will display it in the field below. Now click on the ‘Create’ button to add your wildcard subdomain.

Enabling WordPress Multisite Network Feature

Multisite Network feature comes built-in with each WordPress install. All you need to do is install and setup WordPress like you normally would. After that, you just need to enable the multisite feature.

You can also enable multisite feature on any existing WordPress site. Before you enable multisite, don’t forget to create a complete backup of your WordPress site.

To enable Multisite, connect to your site using a FTP client or cPanel file manager, and open the wp-config.php file for editing.

You need to add the following code to your wp-config.php file just before the /* That’s all, stop editing! Happy blogging. */ line.

/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );

Now save and upload your wp-config.php file back to the server.

This code simply enables multisite feature on your WordPress site. You would still need to setup multisite, and how you want to use it.

Setting up Your WordPress Multisite Network

Now that you have successfully enabled the Multisite Network feature on your WordPress site, it is time to set up your network.

Before you do that, you will need to deactivate all plugins on your WordPress site.

Visit Plugins » Installed Plugins page and select all plugins. From ‘Bulk Actions’ drop down menu select ‘Deactivate’ and then click on the ‘Apply’ button.

Deactivate all plugins

You can now head over to Tools » Network Setup page to configure your multisite network.

WordPress multisite network setup

On the network setup screen, you will see a notice that you need Apache’s mod_rewrite module installed on your server. This module is installed and enabled on all best WordPress hosting providers.

The next thing you need to do is to tell WordPress what kind of domain structure you will be using for sites in your network, e.g. Subdomains or Sub-directories.

After that you would need to provide a title for your network and make sure that the email address in the Network admin email is correct.

Lastly, click on the install button to continue.

WordPress will now show you some code that you need to add to your wp-config.php and .htaccess file.

Add code to wp-config and .htaccess files

Use your FTP client or file manager cPanel to copy and paste the code in these two files.

After that you will need to login to your WordPress site again.

Configuring Network Settings

Now that you have setup the multisite network, it is time to configure network settings.

To do that, you need to switch to the ‘Network Dashboard’ to change network settings, add new sites, and configure other settings.

When you take your mouse over to the ‘My Sites’ menu in the admin toolbar, a flydown popup will appear. Click on the Network Admin » Dashboard.

Network admin dashboard

You will notice that there are new menu items to manage your multisite network. You will also see a dashboard widget allowing you to create new site and add new users.

Network dashboard

To configure network settings, click on the ‘Settings’ link in the admin sidebar.

The first option on network settings page is to set your site title and admin email address. These fields will be filled with the network title and admin email you entered during setup.

Network settings

Opening Your Multisite Network for Registrations

The ‘Registration Settings’ section on the network settings screen is probably the most important setting in your network setup.

By default, both user and site registrations are disabled on the network.

You can choose to open your site for user registration, or allow existing users to create new sites, or allow both user and site registration.

WordPress multisite registration settings

If you are opening your multisite network to registration, then you can check the box next to ‘Registration Notification’ option to receive email notifications every time a new user or site is registered.

If you want to allow individual site administrators the ability to add new users on their sites, then you can check the box next to ‘Add New Users’ option.

Registration options

Limited Email Registration option allows you to limit site or user registration to email addresses from specific domains. This is particularly useful if you only want to allow people from your own organization to register and create users or sites.

Similarly, you can also ban certain domains from registration.

New Site Settings

The ‘New Site Settings’ section allows you to configure default options for new sites created on your network. You can modify the welcome emails and the contents of first default post, page, and comment.

New site settings

Upload Settings for Your Multisite Network

It is important for you to keep an eye on the usage of the server resources. Under the Upload Settings section, you can limit the total amount of space a site can use for uploads.

The default value is 100 MB which is probably good for at least 100 photo uploads. You can increase or decrease this space depending on how much disk space you have.

Upload settings

The default upload file types are images, audio, video, and pdf files. You can add additional file types if you want, e.g. doc docx odt.

Lastly, you can choose a file size limit, so that users can’t upload insanely large files to the server.

Plugin Menu Settings

Under the menu settings, you will find the option to enable administrative menu for the plugins section on the network sites.

Enabling this will show plugins menu to respective site admins. They can activate or deactivate a plugin on their individual sites, but they cannot install new plugins.

Show or hide plugins menu to site admins

Adding New Sites to Your WordPress Multisite Network

To add a new site to your WordPress multisite, simply click on Sites under My Sites » Network Admin menu in the admin toolbar.

Adding new sites to your WordPress multisite network

This will show you a list of sites on your current multisite installation. By default, you have your primary site listed as the only site in your WordPress Multisite network.

To add a new site, click on the Add New button at the top.

Add new site

On the ‘Add New Site’ page, you need to provide the site’s address. You don’t need to type the full address, just the part you want to use as subdomain or sub-directory.

After that provide a site title, and add the site admin’s email address.

Adding new site details

You can add an admin email address other than the one you are currently using to manage your multisite.

If the email address is not currently in use by another user, then WordPress will create a new user and send the password and username to the email address you enter.

Once you are done, click on the ‘Add Site’ button.

A new site will be added to your multisite network. As the network admin, you will receive a new site registration email.

If you created a new user, then that user will receive an email with instructions to set password and login.

Adding Themes and Plugins to Your Multisite Network

By default, individual site administrators in a multisite network cannot install themes and plugins on their own.

As the network admin, you can install plugins and themes and make those themes / plugins available to them.

To add themes, go to My Sites » Network Admin » Themes page.

Installed themes on your WordPress multisite network

Now you will see a list of currently installed themes on your WordPress multisite. You can make a theme available to other sites by clicking on ‘Enable Network’ under that theme. You can also disable a theme by clicking on Disable Network link under the theme.

To add a new theme, you need to click on the ‘Add New’ button at the top and then install a theme like you would normally do.

Once the new theme is installed, you will be able to make it available to other sites on your network.

Similarly, you can install plugins and network activate them by visiting My Sites » Network Admin » Plugins page.

Network activate plugins on a WordPress multisite

Note: If you have enabled Plugins Menu for site admins in the ‘Network Settings’, then site administrators can activate or deactivate installed plugins on their own.

Troubleshooting WordPress Multisite Issues

Most common issues occur due to incorrect configuration of wildcard subdomains. Make sure that your web host supports wildcard subdomains.

Another common issue is that when using WordPress multisite with sub-directories, some users are unable to login to the admin area of their sites after they add the required code in wp-config.php file. To fix this, try replacing

define('SUBDOMAIN_INSTALL', false);

line in wp-config.php file with

define('SUBDOMAIN_INSTALL', 'false');

One more issue that you may came across is not being able to find the users who registered but didn’t get the activation email. To fix this issue, see our guide on how to find pending unconfirmed users in WordPress.

Later at some point you or another site owner may want to export a site from multisite to its own WordPress install. This can be easily done. For step by step instructions see our guide on how to move a site from WordPress multisite to single install.

We hope this article helped you lean how to install and setup WordPress multisite network. You may also want to see our step by step WordPress security guide to protect and keep your WordPress multisite secure.

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 Install and Setup WordPress Multisite Network appeared first on WPBeginner.

How to Change the Category Base Prefix in WordPress

Do you want to change the category base prefix in WordPress? By default, WordPress automatically adds /category/ as a prefix to URLs for all category pages. In this article, we will show you how to change the category base prefix in WordPress. We will also… Read More »

The post How to Change the Category Base Prefix in WordPress appeared first on WPBeginner.

Do you want to change the category base prefix in WordPress? By default, WordPress automatically adds /category/ as a prefix to URLs for all category pages. In this article, we will show you how to change the category base prefix in WordPress. We will also talk about whether or not you should remove the base prefix altogether.

How to change the category base prefix in WordPress

What is Category Base Prefix? Should You Change It?

Each category on your WordPress site get its own page and RSS feed. You can view all posts filed under a category by visiting that category archive page.

By default, WordPress adds ‘category’ as base prefix to URLs for category pages. This helps differentiate pages and posts from category and tag archives.

For example, if you have a category called ‘News’ then its URL will look like this:

http://example.com/category/news/

Similarly, WordPress also adds tag prefix to URLs for tag archives.

http://example.com/tag/iphone/

This SEO friendly URL structure helps users and search engines understand what kind of page they are visiting.

Most websites don’t need to change the base prefix at all. However, if you are creating a niche site where you would like to use a different word or phrase for your categories, then you can change the category base prefix to reflect that.

Changing Category Base Prefix in WordPress

Changing category base prefix is quite simple in WordPress.

You need to visit Settings » Permalinks page and scroll down to the ‘Optional’ section.

Changing category base prefix in permalink settings

Here you can enter the prefix you would like to use next to the category base option. You can also change the tag base prefix if you want.

Don’t forget to click on the save changes button to store your settings.

Setting up Redirects After Changing Category Base Prefix

If you are changing category base prefix on a new website, then you don’t need to do anything. However, if you are doing this on an existing website, then users visiting the old category page will see a 404 error.

To fix this, you will need to setup redirect to make sure both search engines and regular visitors are properly redirected to the correct category page on your site.

First you will need to install and activate the Redirection plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Tools » Redirection page to setup redirect.

Setting up redirect after changing category prefix

Scroll down to ‘Add new redirection’ section.

First, you need to add /category/(.*) in the source URL field. After that you need to check the box next to the regular expression option.

In the target URL field, you need to add your new category base prefix like this /topics/$1. Don’t forget to replace topics with your new category prefix.

Click on the ‘Add Redirection’ button to save your changes.

That’s all. Now all your users and search engines will be redirected to the correct URLs using your new category prefix.

Removing The Category Base Prefix in WordPress

Many of our users have asked us about removing the category base prefix from WordPress URLs altogether. This will change your category URLs to look like this:

http://example.com/news/

This is not a good idea, and we recommend that you do not remove category base prefix.

Category base prefix helps both users and search engines distinguish between posts/pages and categories. Removing the prefix makes your URLs ambiguous which is not good for user experience or SEO.

You may also run into technical issues with various WordPress plugins. For example, if you have a category and a page with the same name or when you are using %postname% as your URL structure for single posts, then your site will experience infinite redirect loop causing the pages to never load.

However, if you still want to do this, then you need to install and activate FV Top Level Categories plugin. For more details, see our step by step guide on how to install a WordPress plugin.

The plugin works out of the box and will immediately remove the category base prefix from your category URLs.

We hope this article helped you learn how to change the category base prefix in WordPress. You may also want to see our list of most wanted WordPress tips, tricks, and hacks.

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 Change the Category Base Prefix in WordPress appeared first on WPBeginner.

How to Use Social Media to Boost Email Subscribers in WordPress

Do you want to use social media to increase your email subscribers? If you’re not taking advantage of your social media following to build your email list, then you’re missing out on a huge opportunity. In this article, we’ll discuss why email and social media… Read More »

The post How to Use Social Media to Boost Email Subscribers in WordPress appeared first on WPBeginner.

Do you want to use social media to increase your email subscribers? If you’re not taking advantage of your social media following to build your email list, then you’re missing out on a huge opportunity. In this article, we’ll discuss why email and social media integration is so important for every business, and show you how to use social media to boost email subscribers in WordPress.

Using social media to increase email subscribers

Email Marketing vs. Social Media – Which Is Better?

One of the most common questions we get asked from new business owners is which is better when it comes to email marketing vs social media?

Social media platforms offer a great opportunity to interact with your users and keep them engaged. However, nothing beats email marketing when it comes to engagement.

First, email marketing is very cost effective. For every $1 spent, email marketing generates $38 in return. On the other hand, less than half of marketers agree that social media gives them any return on investment at all.

Social platforms like Facebook tightly control your reach to your own followers. Only about 2% of your Facebook fans will see your updates. Even your tweets are visible to the user for a very short time before it gets pushed down by other tweets. Social media platforms also retain the right to block your account at any time, for any reason.

Even if social media marketing is working well for you now, that’s not guaranteed to last. Social media websites come and go (no one uses Friendster, MySpace, or Digg anymore). When they disappear, all the hard work you put into building a following is gone too.

Email gives you direct access to your subscribers. Most importantly, you own your email list and no one can take away your users.

We’re not saying that you shouldn’t use social media to promote your website. However, your focus should be more on building an email list for higher ROI and long term marketing goals.

Many successful website owners will tell you that not starting an email list was the biggest mistake they made when starting out. See our article on why building your email list is so important today for more on this topic.

Convinced about the importance of your email list? Let’s see how you can leverage your social media profiles to get even more email subscribers.

What Do You Need to Start Building Your Email List?

There are three things you will need to start building your email list.

  • A website or blog
  • An email marketing service
  • Lead generation software

All three of them are quite easy to set up without learning any technical skills.

If you don’t have a website or blog yet, then see our step by step guide on how to start a blog.

You will also need an email marketing service. It helps you collect email addresses, manage your email lists, and send out emails. Most importantly, using an email marketing service will help you to stay compliant with email spam laws, and ensure that your emails don’t end up in the spam folder.

We recommend using Constant Contact. It is one of the largest and most popular email marketing services in the world. For more recommendations, see our list of the best email marketing services for small business.

Lastly, you will need a lead generation software like OptinMonster. It’s the most effective way to convert website visitors and social media followers into email subscribers. See our case study of how we increased our email subscribers by 600% with OptinMonster.

Once you’ve got your website, email newsletter, and lead generation software set up, you can get started with these email and social media integration techniques.

1. Collect Email Addresses From Your Facebook Page

If you have a successful Facebook page, you may have a lot of fans who have never visited your website before. An easy way to convert those fans into subscribers is by adding a prominent link right to an email signup form.

Luckily, Facebook has made this easy by introducing call to action buttons for business pages. These buttons are prominently displayed on top of your cover image and are visible without scrolling.

Call to action button on a Facebook business page

To add a signup button to your Facebook page, you’ll need to visit your Facebook page and click the blue Add a button button.

Adding a call to action button

This will bring up a popup with multiple choices. You need to click on the Get in touch with us tab and then select Sign up.

Next, you need to provide a link to your website where users will be taken when they click signup.

Add a link to your sign up page

The link should be to a page on your website that features an email signup form. Don’t forget to click on add button to save your changes.

That’s all! Visitors to your Facebook page will now see a prominent call to action button leading them to sign up for your email list.

2. Use Facebook Retargeting/Remarketing Pixel

Facebook retargeting pixel

Have you noticed that after you visit a website, you often start seeing their ads on Facebook?

This is called retargeting or remarketing. Those websites use Facebook’s retargeting technology, commonly known as Facebook Pixel.

The retargeting pixel does not add anything visible to your website visitors. It simply sends a browser cookie to your visitors, so that Facebook can recognize them.

After your website visitors leave your site and go on Facebook, they’ll see your ads targeted just to them.

Follow our step by step guide on how to install Facebook retargeting/remarketing pixel in WordPress. Then, check out these tips for optimizing your Facebook ads for conversions.

3. Use Facebook Ads to Promote Pages with Special Offers

Often people are hesitant to give out their email addresses, but become much more willing to share when you offer them something of value in exchange.

These special offers in exchange for email addresses are also called lead magnets. Common lead magnets include e-books, cheat sheets, templates, reports, coupons, and more. The more targeted your offer is towards a specific audience, the more email addresses you’ll get.

You can create a landing page or blog post on your website that features your lead magnet, and use an OptinMonster campaign to capture email addresses. Here’s a guide on how to create your first OptinMonster campaign to build your email list.

Then, create an ad on Facebook for your free special offer that links to your landing page. This technique is even more powerful when combined with Facebook retargeting, because you’re advertising to people who have already displayed an interest in what you have to offer.

4. Add Links to Your Signup Pages in YouTube Videos

Add links to your website in YouTube videos
Do you run a YouTube channel? You can stay in touch with your viewers by adding calls to action and URLs right in your videos.

Again, it’s smart to offer an incentive for users to click on the links. Many online marketers do that by offering bonus content, learning material, coupons, and special discounts.

You can easily add a link to your video by going to your Video Manager, then clicking on Edit » Cards » Add card. Then you can add a link to your website.

Once the user lands on your website, you can use a landing page with an OptinMonster campaign to show them targeted offers. OptinMonster’s referral detection feature makes it easy to target your campaign so that only your YouTube fans will see it.

5. Run Twitter Ad Campaign

Twitter Ads

Twitter Ads is another social platform that you can use to boost your lead generation efforts.

In fact, Twitter even allows you to run lead generation campaigns directly in the user’s Tweet stream. This way users can sign up for your email list without even leaving Twitter.

You can also use Twitter Ads to drive traffic to your website landing page.

6. Promote Old Posts With Targeted Optins

Promote old posts

If you have been blogging for a while, then you already have plenty of content that your new followers may not have seen.

Sharing old posts allows you a chance to share more content with your users on social media platforms. This boosts user engagement on your social profiles, at the same time it brings more traffic to your website.

You can use the Revive Old Post plugin to automatically share your old posts on social media websites. For detailed instructions see our guide on how to automatically share your old WordPress posts.

Then, you can use targeted optins that only display to visitors who click on those older posts. You can use content upgrades, special offers, free downloads, etc.

7. Use Pinterest Boards for Lead Generation

Using Pinterest to increase email subscribers

Pinterest is another powerful social media platform that you can utilize to boost email subscriptions. Similar to Facebook and Twitter, you can offer your Pinterest followers content upgrades, coupons, and discounts.

You can also offer free downloads like ebooks, PDFs, audio or video content, and display a welcome gate to entice visitors to subscribe as soon as they visit your site.

9. Ask Influencers to Share Links to Your Special Offers

Don’t just keep your special offers limited to your own social profiles. Ask your friends, family, and followers to share your special offers.

You can also reach out to influential users that you are connected with and ask if they can help you spread the word. People love to help out, but they will not be able to do that if you don’t ask them.

Your offer becomes more valuable when it is recommended by influencers. It makes users feel that they can trust you with their information.

That’s all for now. We hope this article helped you learn how to use social media to increase email subscribers in WordPress. You may also want to see our list of the best social media plugins for WordPress, and check out this beginner’s guide on how to build an email list in WordPress for more tips.

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 Use Social Media to Boost Email Subscribers in WordPress appeared first on WPBeginner.

WordPress Custom Fields 101: Tips, Tricks, and Hacks

Ever wondered what are custom fields in WordPress? Want to learn more about how custom fields work? In this article, we will show you how to user WordPress custom fields with tips, tricks, and hacks. Since this is a lengthy article, we have added table… Read More »

The post WordPress Custom Fields 101: Tips, Tricks, and Hacks appeared first on WPBeginner.

Ever wondered what are custom fields in WordPress? Want to learn more about how custom fields work? In this article, we will show you how to user WordPress custom fields with tips, tricks, and hacks.

Custom Fields 101

Since this is a lengthy article, we have added table of contents for easier navigation.

What are WordPress Custom Fields?

WordPress custom fields are metadata that are used to add additional information related to the post or page such as title, author name, date / time, etc.

By default, when you write a new post, page, or any content type, WordPress saves it into two different areas. The first part is the body of your content that you add using the post editor.

The second part is the information about that particular content. For example, title, author, date, time, and more. This information bit of the post is called metadata.

WordPress automatically adds all the required metadata to each post or page you create. WordPress also allows users to save their own custom metadata using custom fields.

By default, custom fields option is hidden on the post edit screen. To view it, you need to click on the ‘Screen Options’ button at the top and then check the custom fields option.

Show custom fields meta box

Scroll down a little, and you will be able to see the custom field meta box below the post editor.

Custom fields meta box on post edit screen in WordPress

Custom fields can be used to add any information related to the post, page, or any content type. This meta information can be displayed in your theme. However, to do that you will need to edit your WordPress theme files.

This is why this tutorial is recommended for users familiar with editing theme files. It is also helpful for aspiring WordPress developers who want to learn how to properly use custom fields in their own themes or plugins.

Having said that, let’s take a look at how to add and use custom fields in WordPress.

Adding Custom Fields in WordPress

First you need to edit the post or page where you want to add the custom field and go to the custom fields meta box.

Adding custom field

Next, you need to provide a name for your custom field and then enter its value. Click on the Add Custom Field button to save it.

The field will be stored and displayed in the custom fields meta box like this:

Saved custom field

You can edit this custom field any time you want and then click on the update button to save your changes. You can also delete it as needed.

Now you can save your post to store your custom field settings.

Displaying Custom Fields in WordPress Themes

To display your custom field on your website, you will need to edit your WordPress theme files. If you haven’t done this before, then take a look at our guide on how to copy and paste code in WordPress.

First you will need to find the theme file you need to edit to display your custom field. Ideally you would want to display it on a single post page. You will need to edit the single.php or content-single.php file.

You will need to enter your custom fields code inside the WordPress loop. Look for the line that looks like this:

<?php while ( have_posts() ) : the_post(); ?>

You want to make sure that you add your code before the following line:

<?php endwhile; // end of the loop. ?>

Now you need to add this code to your theme file:

<?php echo get_post_meta($post->ID, 'key', true); ?>

Don’t forget to replace key with the name of your custom field. For example, we used this code in our demo theme:

<p>Today's Mood: <?php echo get_post_meta($post->ID, 'Mood', true); ?></p>

You can now save your changes and visit the post where you added the custom field to see it in action.

Custom field data displayed in a WordPress theme

Now you can use this custom field in all your other WordPress posts as well. Simply create a new post or edit an existing one. Go to the custom fields meta box and select your custom field from the drop down menu and enter its value.

Select and reuse custom field

Click on ‘Add Custom Field’ button to save your changes and then publish or update your post.

Creating a User Interface for Custom Fields

As you can see, that once you add a custom field, you will have to select the field and enter its value each time you write a post.

If you have many custom fields or multiple users writing on your website, then this is not a very ideal solution.

Wouldn’t it be nice if you could create a user interface where users can fill in a form to add values into your custom fields?

This is what so many popular plugins already do. For example, the SEO title and meta description box inside Yoast SEO plugin is a custom meta box:

Custom meta box used in Yoast SEO

The easiest way to do this is by using the Advanced Custom Fields plugin. It allows you to create custom fields, group them, and display them in a custom meta box on your post edit screens in WordPress.

For detailed step by step instructions, see our guide on how to add custom meta boxes in WordPress posts and post types.

Hide Empty Custom Fields with Conditional Statement

In the above example, we showed you how to create a custom field and display it in your theme.

Now let’s see how to check if the custom field is not empty before displaying it. To do that, we will modify our code to first check if the field has data in it.

<?php 

$mood = get_post_meta($post->ID, 'Mood', true);

if ($mood) { ?>

<p>Today's Mood: <? echo $mood; ?></p>

<?php 

} else { 
// do nothing; 
}

?>

Don’t forget to replace Mood with your own custom field name.

Adding Multiple Values to a Custom Field

Custom fields can be reused in the same post again to add multiple values. You just need to select it again and add another value.

Adding multiple values to a custom field

However, the code we have used in above examples will only be able to show a single value.

To display all values of a custom field, we need to modify the code and make it return the data in an array. You will need to add the following code in your theme file:

<?php 
$mood = get_post_meta($post->ID, 'Mood', false);
if( count( $mood ) != 0 ) { ?>
<p>Today's Mood:</p>
<ul>
<?php foreach($mood as $mood) {
            echo '<li>'.$mood.'</li>';
            }
            ?>
</ul>
<?php 
} else { 
// do nothing; 
}
?>

Don’t forget to replace Mood with your own custom field name.

In this example, you would notice that we have changed the last parameter of get_post_meta function to false. This parameter defines whether the function should return a single value or not. Setting it to false allows it to return the data as an array, which we then displayed in a foreach loop.

Displaying Posts with a Specific Custom Key

WordPress allows you to display posts with custom keys and their values. For example, if you are trying to create a custom archive page to display all posts with specific custom keys, then you can use WP_Query class to query posts matching those fields.

You can use the following code as an starting point.

$args = array(
	'meta_key'   => 'Mood',
	'meta_value' => 'Happy'
);
$the_query = new WP_Query( $args );

<?php 
// the query
$the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>

	<!-- the loop -->
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
		<h2><?php the_title(); ?></h2>
		<?php the_content(); ?>

	<?php endwhile; ?>
	<!-- end of the loop -->

	<!-- pagination here -->

	<?php wp_reset_postdata(); ?>

<?php else : ?>
	<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Don’t forget to replace meta_key and meta_value parameters with your own values.

Add Guest Author Name Using Custom Fields

Do you want to add a guest post but don’t want to add a new user profile just to add a single post? An easier way to do that is by adding guest author name as a custom field.

First, you need to add the following code in your theme’s functions.php file or a site-specific plugin.

add_filter( 'the_author', 'guest_author_name' );
add_filter( 'get_the_author_display_name', 'guest_author_name' );
function guest_author_name( $name ) {
global $post;
$author = get_post_meta( $post->ID, 'guest-author', true );
if ( $author )
$name = $author;
return $name;
}

This code hooks a function to the_author and get_the_author_display_name filters in WordPress. The function first checks for the guest author name. If it exists, then it replaces the author name with the guest author name.

Now you will need to edit the post where you want to display the guest author name. Go to the custom fields meta box and add your guest author name.

Adding guest author custom field

For details, see our article on how to rewrite guest author name with custom fields in WordPress.

Display Contributors to an Article Using Custom Fields

On many popular blogs and news sites, multiple authors contribute to write an article. However, WordPress only allows a single author to be associated with a post.

One way to solve this problem is by using Co-Authors Plus plugin. To learn more, see our guide on how to add multiple authors on a WordPress post.

Another way to do that is by adding contributors as a custom field.

First you need to edit the post where you want to display co-authors or contributors. Scroll down to custom fields meta box and add author names as co-author custom field.

Adding co-authors as custom field

Now add this code to your theme files where you want to show co-authors.


<?php 

$coauthors = get_post_meta($post->ID, 'co-author', false);
if( count( $coauthors ) != 0 ) { ?>
<ul class="coauthors">
<li>Contributors</li>
<?php foreach($coauthors as $coauthors) { ?>
           <?php echo '<li>'.$coauthors.'</li>' ;
            }
            ?>
</ul>
<?php 
} else { 
// do nothing; 
}
?>

To display author names separated by commas, you can add the following custom CSS.

.coauthors ul { 
display:inline;
}
.coauthors li { 
display:inline;
list-style:none;
}
.coauthors li:after { 
content:","
}
.coauthors li:last-child:after {
    content: "";
}
.coauthors li:first-child:after {
    content: ":";
}

This is how it looked on our demo site.

Co-authors displayed using custom fields

Display Custom Fields Outside the Loop in WordPress

So far we have shown you all the examples where custom fields are displayed inside the WordPress loop. What if you needed to show them outside the loop? For example, in the sidebar of a single post.

To display the custom fields outside the WordPress loop add the following code:

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'key', true);
wp_reset_query();
?>

Don’t forget to replace the key with your custom field name.

Display Custom Header, Footer, Sidebar using Custom Fields

Usually most WordPress themes use the same header, footer, and sidebar on all pages. There are multiple ways to show different sidebars, header, or footer for different pages on your website. See our guide on how to display different sidebar for each WordPress post or page.

One way to do this is by using custom fields. Edit the post or page where you want to show a different sidebar and then add the sidebar as custom field.

Adding custom sidebar to a post using custom fields

Now you need to edit your WordPress theme files like single.php where you want to display custom sidebar. You will be looking for the following code:

<?php get_sidebar(); ?>

Replace this line with the following code:

<?php 
global $wp_query;
$postid = $wp_query->post->ID;
$sidebar = get_post_meta($postid, "sidebar", true);
get_sidebar($sidebar);
wp_reset_query();
?>

This code simply looks for the sidebar custom field and then displays it in your theme. For example, if you add wpbpage as your sidebar custom field, then the code will look for sidebar-wpbpage.php file to display.

You will need to create sidebar-wpbpage.php file in your theme folder. You can copy the code from your theme’s sidebar.php file as an starting point.

Manipulating RSS feed Content with Custom Fields

Want to display additional meta data or content to your RSS feed users? Using custom fields you can manipulate your WordPress RSS feed and add custom content into your feeds.

First you need to add the following code in your theme’s functions.php file or a site-specific plugin.

function wpbeginner_postrss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$coolcustom = get_post_meta($postid, 'coolcustom', true);
if(is_feed()) {
if($coolcustom !== '') {
$content = $content."<br /><br /><div>".$coolcustom."</div>
";
}
else {
$content = $content;
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpbeginner_postrss');
add_filter('the_content', 'wpbeginner_postrss');

Now just create a custom field called “coolcustom” and add any value you like. You can use it to display advertisements, images, text, or anything you want.

Manipulate RSS Feed Title with Custom Fields

Sometimes you may want to add extra text to a post title for RSS feed users. For example, if you are publishing a sponsored post or a guest post.

First you add the following code in your theme’s functions.php file or a site-specific plugin.

function wpbeginner_titlerss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$gpost = get_post_meta($postid, 'guest_post', true);
$spost = get_post_meta($postid, 'sponsored_post', true);

if($gpost !== '') {
$content = 'Guest Post: '.$content;
}
elseif ($spost !== ''){
$content = 'Sponsored Post: '.$content;
}
else {
$content = $content;
}
return $content;
}
add_filter('the_title_rss', 'wpbeginner_titlerss');

Next, you need to edit the post where you want to display the extra text in the title field and add guest_post and sponsored_post in custom fields.

 Sponsored and guest post custom fields

If any of these two custom fields are found with a value “true”, then it will add the appropriate text before the title. This technique can be utilized in various ways to fit whatever you like.

Want to learn more cool RSS feed hacks? See our guide on how to add content and manipulate your WordPress RSS feeds.

Set Expiration Date for Posts in WordPress Using Custom Fields

Want to set an expiration date for some posts on your WordPress site? This comes handy in situations when you want to publish content only for a specific period like running surveys or limited time offers.

One way to do this is by manually removing the post content or by using a plugin like Post Expirator plugin.

Another way to do this is by using custom fields to automatically expire posts after a specific time.

You will need to edit your theme files and add modify the WordPress loop like this:

<?php
if (have_posts()) :
while (have_posts()) : the_post(); 
$expirationtime = get_post_meta($post->ID, "expiration", false);
if( count( $expirationtime ) != '' ) { 
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}

$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween >= 0 ) {
echo 'This post will expire on ' .$expirestring.'';
the_content();
} else { 
echo "Sorry this post expired!"
}
} else { 
the_content();
} 
endwhile;
endif;
?>

Note: You will need to edit this code to match your theme.

After adding this code, you can add the expiration custom field to the post you want to expire. Make sure you add the time in this format mm/dd/yyyy 00:00:00.

Adding an expiration custom field to a WordPress post

Style Individual Posts Using Custom Fields

Want to change the look of an individual post using CSS? WordPress automatically assigns each post its own class which you can use to add custom CSS.

However, using custom fields you can add your own custom classes and then use them to style posts differently.

First you need to edit a post that you would like to style differently. Go to custom fields box and the post-class custom field.

Post class custom field

Next, you need to edit your WordPress theme files and add this code at the beginning of WordPress loop.

<?php $custom_values = get_post_meta($post->ID, 'post-class'); ?>

Now you need to find a line with the post_class() function. Here is how it looked in our demo theme:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Change this line to include your custom field value, like this:

<article id="post-<?php the_ID(); ?>" <?php post_class($custom_values); ?>>

Now if you examine the post’s source code using Inspect tool, then you will see your custom field CSS class added to the post class.

Custom field post class

Now you can use this CSS class to add custom CSS and style your post differently.

That’s all, we hope this article helped you learn more about WordPress custom fields. You may also want to see our ultimate step by step guide to boost WordPress speed and performance for beginners.

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 WordPress Custom Fields 101: Tips, Tricks, and Hacks appeared first on WPBeginner.

WordPress Custom Fields 101: Tips, Tricks, and Hacks

Ever wondered what are custom fields in WordPress? Want to learn more about how custom fields work? In this article, we will show you how to user WordPress custom fields with tips, tricks, and hacks. Since this is a lengthy article, we have added table… Read More »

The post WordPress Custom Fields 101: Tips, Tricks, and Hacks appeared first on WPBeginner.

Ever wondered what are custom fields in WordPress? Want to learn more about how custom fields work? In this article, we will show you how to user WordPress custom fields with tips, tricks, and hacks.

Custom Fields 101

Since this is a lengthy article, we have added table of contents for easier navigation.

What are WordPress Custom Fields?

WordPress custom fields are metadata that are used to add additional information related to the post or page such as title, author name, date / time, etc.

By default, when you write a new post, page, or any content type, WordPress saves it into two different areas. The first part is the body of your content that you add using the post editor.

The second part is the information about that particular content. For example, title, author, date, time, and more. This information bit of the post is called metadata.

WordPress automatically adds all the required metadata to each post or page you create. WordPress also allows users to save their own custom metadata using custom fields.

By default, custom fields option is hidden on the post edit screen. To view it, you need to click on the ‘Screen Options’ button at the top and then check the custom fields option.

Show custom fields meta box

Scroll down a little, and you will be able to see the custom field meta box below the post editor.

Custom fields meta box on post edit screen in WordPress

Custom fields can be used to add any information related to the post, page, or any content type. This meta information can be displayed in your theme. However, to do that you will need to edit your WordPress theme files.

This is why this tutorial is recommended for users familiar with editing theme files. It is also helpful for aspiring WordPress developers who want to learn how to properly use custom fields in their own themes or plugins.

Having said that, let’s take a look at how to add and use custom fields in WordPress.

Adding Custom Fields in WordPress

First you need to edit the post or page where you want to add the custom field and go to the custom fields meta box.

Adding custom field

Next, you need to provide a name for your custom field and then enter its value. Click on the Add Custom Field button to save it.

The field will be stored and displayed in the custom fields meta box like this:

Saved custom field

You can edit this custom field any time you want and then click on the update button to save your changes. You can also delete it as needed.

Now you can save your post to store your custom field settings.

Displaying Custom Fields in WordPress Themes

To display your custom field on your website, you will need to edit your WordPress theme files. If you haven’t done this before, then take a look at our guide on how to copy and paste code in WordPress.

First you will need to find the theme file you need to edit to display your custom field. Ideally you would want to display it on a single post page. You will need to edit the single.php or content-single.php file.

You will need to enter your custom fields code inside the WordPress loop. Look for the line that looks like this:

<?php while ( have_posts() ) : the_post(); ?>

You want to make sure that you add your code before the following line:

<?php endwhile; // end of the loop. ?>

Now you need to add this code to your theme file:

<?php echo get_post_meta($post->ID, 'key', true); ?>

Don’t forget to replace key with the name of your custom field. For example, we used this code in our demo theme:

<p>Today's Mood: <?php echo get_post_meta($post->ID, 'Mood', true); ?></p>

You can now save your changes and visit the post where you added the custom field to see it in action.

Custom field data displayed in a WordPress theme

Now you can use this custom field in all your other WordPress posts as well. Simply create a new post or edit an existing one. Go to the custom fields meta box and select your custom field from the drop down menu and enter its value.

Select and reuse custom field

Click on ‘Add Custom Field’ button to save your changes and then publish or update your post.

Creating a User Interface for Custom Fields

As you can see, that once you add a custom field, you will have to select the field and enter its value each time you write a post.

If you have many custom fields or multiple users writing on your website, then this is not a very ideal solution.

Wouldn’t it be nice if you could create a user interface where users can fill in a form to add values into your custom fields?

This is what so many popular plugins already do. For example, the SEO title and meta description box inside Yoast SEO plugin is a custom meta box:

Custom meta box used in Yoast SEO

The easiest way to do this is by using the Advanced Custom Fields plugin. It allows you to create custom fields, group them, and display them in a custom meta box on your post edit screens in WordPress.

For detailed step by step instructions, see our guide on how to add custom meta boxes in WordPress posts and post types.

Hide Empty Custom Fields with Conditional Statement

In the above example, we showed you how to create a custom field and display it in your theme.

Now let’s see how to check if the custom field is not empty before displaying it. To do that, we will modify our code to first check if the field has data in it.

<?php 

$mood = get_post_meta($post->ID, 'Mood', true);

if ($mood) { ?>

<p>Today's Mood: <? echo $mood; ?></p>

<?php 

} else { 
// do nothing; 
}

?>

Don’t forget to replace Mood with your own custom field name.

Adding Multiple Values to a Custom Field

Custom fields can be reused in the same post again to add multiple values. You just need to select it again and add another value.

Adding multiple values to a custom field

However, the code we have used in above examples will only be able to show a single value.

To display all values of a custom field, we need to modify the code and make it return the data in an array. You will need to add the following code in your theme file:

<?php 
$mood = get_post_meta($post->ID, 'Mood', false);
if( count( $mood ) != 0 ) { ?>
<p>Today's Mood:</p>
<ul>
<?php foreach($mood as $mood) {
            echo '<li>'.$mood.'</li>';
            }
            ?>
</ul>
<?php 
} else { 
// do nothing; 
}
?>

Don’t forget to replace Mood with your own custom field name.

In this example, you would notice that we have changed the last parameter of get_post_meta function to false. This parameter defines whether the function should return a single value or not. Setting it to false allows it to return the data as an array, which we then displayed in a foreach loop.

Displaying Posts with a Specific Custom Key

WordPress allows you to display posts with custom keys and their values. For example, if you are trying to create a custom archive page to display all posts with specific custom keys, then you can use WP_Query class to query posts matching those fields.

You can use the following code as an starting point.

$args = array(
	'meta_key'   => 'Mood',
	'meta_value' => 'Happy'
);
$the_query = new WP_Query( $args );

<?php 
// the query
$the_query = new WP_Query( $args ); ?>

<?php if ( $the_query->have_posts() ) : ?>

	<!-- the loop -->
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
		<h2><?php the_title(); ?></h2>
		<?php the_content(); ?>

	<?php endwhile; ?>
	<!-- end of the loop -->

	<!-- pagination here -->

	<?php wp_reset_postdata(); ?>

<?php else : ?>
	<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

Don’t forget to replace meta_key and meta_value parameters with your own values.

Add Guest Author Name Using Custom Fields

Do you want to add a guest post but don’t want to add a new user profile just to add a single post? An easier way to do that is by adding guest author name as a custom field.

First, you need to add the following code in your theme’s functions.php file or a site-specific plugin.

add_filter( 'the_author', 'guest_author_name' );
add_filter( 'get_the_author_display_name', 'guest_author_name' );
function guest_author_name( $name ) {
global $post;
$author = get_post_meta( $post->ID, 'guest-author', true );
if ( $author )
$name = $author;
return $name;
}

This code hooks a function to the_author and get_the_author_display_name filters in WordPress. The function first checks for the guest author name. If it exists, then it replaces the author name with the guest author name.

Now you will need to edit the post where you want to display the guest author name. Go to the custom fields meta box and add your guest author name.

Adding guest author custom field

For details, see our article on how to rewrite guest author name with custom fields in WordPress.

Display Contributors to an Article Using Custom Fields

On many popular blogs and news sites, multiple authors contribute to write an article. However, WordPress only allows a single author to be associated with a post.

One way to solve this problem is by using Co-Authors Plus plugin. To learn more, see our guide on how to add multiple authors on a WordPress post.

Another way to do that is by adding contributors as a custom field.

First you need to edit the post where you want to display co-authors or contributors. Scroll down to custom fields meta box and add author names as co-author custom field.

Adding co-authors as custom field

Now add this code to your theme files where you want to show co-authors.


<?php 

$coauthors = get_post_meta($post->ID, 'co-author', false);
if( count( $coauthors ) != 0 ) { ?>
<ul class="coauthors">
<li>Contributors</li>
<?php foreach($coauthors as $coauthors) { ?>
           <?php echo '<li>'.$coauthors.'</li>' ;
            }
            ?>
</ul>
<?php 
} else { 
// do nothing; 
}
?>

To display author names separated by commas, you can add the following custom CSS.

.coauthors ul { 
display:inline;
}
.coauthors li { 
display:inline;
list-style:none;
}
.coauthors li:after { 
content:","
}
.coauthors li:last-child:after {
    content: "";
}
.coauthors li:first-child:after {
    content: ":";
}

This is how it looked on our demo site.

Co-authors displayed using custom fields

Display Custom Fields Outside the Loop in WordPress

So far we have shown you all the examples where custom fields are displayed inside the WordPress loop. What if you needed to show them outside the loop? For example, in the sidebar of a single post.

To display the custom fields outside the WordPress loop add the following code:

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'key', true);
wp_reset_query();
?>

Don’t forget to replace the key with your custom field name.

Display Custom Header, Footer, Sidebar using Custom Fields

Usually most WordPress themes use the same header, footer, and sidebar on all pages. There are multiple ways to show different sidebars, header, or footer for different pages on your website. See our guide on how to display different sidebar for each WordPress post or page.

One way to do this is by using custom fields. Edit the post or page where you want to show a different sidebar and then add the sidebar as custom field.

Adding custom sidebar to a post using custom fields

Now you need to edit your WordPress theme files like single.php where you want to display custom sidebar. You will be looking for the following code:

<?php get_sidebar(); ?>

Replace this line with the following code:

<?php 
global $wp_query;
$postid = $wp_query->post->ID;
$sidebar = get_post_meta($postid, "sidebar", true);
get_sidebar($sidebar);
wp_reset_query();
?>

This code simply looks for the sidebar custom field and then displays it in your theme. For example, if you add wpbpage as your sidebar custom field, then the code will look for sidebar-wpbpage.php file to display.

You will need to create sidebar-wpbpage.php file in your theme folder. You can copy the code from your theme’s sidebar.php file as an starting point.

Manipulating RSS feed Content with Custom Fields

Want to display additional meta data or content to your RSS feed users? Using custom fields you can manipulate your WordPress RSS feed and add custom content into your feeds.

First you need to add the following code in your theme’s functions.php file or a site-specific plugin.

function wpbeginner_postrss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$coolcustom = get_post_meta($postid, 'coolcustom', true);
if(is_feed()) {
if($coolcustom !== '') {
$content = $content."<br /><br /><div>".$coolcustom."</div>
";
}
else {
$content = $content;
}
}
return $content;
}
add_filter('the_excerpt_rss', 'wpbeginner_postrss');
add_filter('the_content', 'wpbeginner_postrss');

Now just create a custom field called “coolcustom” and add any value you like. You can use it to display advertisements, images, text, or anything you want.

Manipulate RSS Feed Title with Custom Fields

Sometimes you may want to add extra text to a post title for RSS feed users. For example, if you are publishing a sponsored post or a guest post.

First you add the following code in your theme’s functions.php file or a site-specific plugin.

function wpbeginner_titlerss($content) {
global $wp_query;
$postid = $wp_query->post->ID;
$gpost = get_post_meta($postid, 'guest_post', true);
$spost = get_post_meta($postid, 'sponsored_post', true);

if($gpost !== '') {
$content = 'Guest Post: '.$content;
}
elseif ($spost !== ''){
$content = 'Sponsored Post: '.$content;
}
else {
$content = $content;
}
return $content;
}
add_filter('the_title_rss', 'wpbeginner_titlerss');

Next, you need to edit the post where you want to display the extra text in the title field and add guest_post and sponsored_post in custom fields.

 Sponsored and guest post custom fields

If any of these two custom fields are found with a value “true”, then it will add the appropriate text before the title. This technique can be utilized in various ways to fit whatever you like.

Want to learn more cool RSS feed hacks? See our guide on how to add content and manipulate your WordPress RSS feeds.

Set Expiration Date for Posts in WordPress Using Custom Fields

Want to set an expiration date for some posts on your WordPress site? This comes handy in situations when you want to publish content only for a specific period like running surveys or limited time offers.

One way to do this is by manually removing the post content or by using a plugin like Post Expirator plugin.

Another way to do this is by using custom fields to automatically expire posts after a specific time.

You will need to edit your theme files and add modify the WordPress loop like this:

<?php
if (have_posts()) :
while (have_posts()) : the_post(); 
$expirationtime = get_post_meta($post->ID, "expiration", false);
if( count( $expirationtime ) != '' ) { 
if (is_array($expirationtime)) {
$expirestring = implode($expirationtime);
}

$secondsbetween = strtotime($expirestring)-time();
if ( $secondsbetween >= 0 ) {
echo 'This post will expire on ' .$expirestring.'';
the_content();
} else { 
echo "Sorry this post expired!"
}
} else { 
the_content();
} 
endwhile;
endif;
?>

Note: You will need to edit this code to match your theme.

After adding this code, you can add the expiration custom field to the post you want to expire. Make sure you add the time in this format mm/dd/yyyy 00:00:00.

Adding an expiration custom field to a WordPress post

Style Individual Posts Using Custom Fields

Want to change the look of an individual post using CSS? WordPress automatically assigns each post its own class which you can use to add custom CSS.

However, using custom fields you can add your own custom classes and then use them to style posts differently.

First you need to edit a post that you would like to style differently. Go to custom fields box and the post-class custom field.

Post class custom field

Next, you need to edit your WordPress theme files and add this code at the beginning of WordPress loop.

<?php $custom_values = get_post_meta($post->ID, 'post-class'); ?>

Now you need to find a line with the post_class() function. Here is how it looked in our demo theme:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Change this line to include your custom field value, like this:

<article id="post-<?php the_ID(); ?>" <?php post_class($custom_values); ?>>

Now if you examine the post’s source code using Inspect tool, then you will see your custom field CSS class added to the post class.

Custom field post class

Now you can use this CSS class to add custom CSS and style your post differently.

That’s all, we hope this article helped you learn more about WordPress custom fields. You may also want to see our ultimate step by step guide to boost WordPress speed and performance for beginners.

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 WordPress Custom Fields 101: Tips, Tricks, and Hacks appeared first on WPBeginner.

How to Embed a Google Form in WordPress

Do you want to embed a Google form in WordPress? Google Forms are easy to embed anywhere and are particularly useful when you need to share the form on multiple websites. In this article, we will show you how to embed a Google form in… Read More »

The post How to Embed a Google Form in WordPress appeared first on WPBeginner.

Do you want to embed a Google form in WordPress? Google Forms are easy to embed anywhere and are particularly useful when you need to share the form on multiple websites. In this article, we will show you how to embed a Google form in WordPress.

How to Embed a Google Form in WordPress

Google Forms vs WordPress Form Builders

Some of you may be thinking that why would anyone want to use Google Forms when there are amazing form builder plugins like WPForms?

It is true, that WordPress form builders are easier to use. They are integrated into your WordPress site, so you can show users a special offer, accept payments, create custom login forms, user registration forms, and more.

However, sometimes you may need to share a form on different websites, email lists, and platforms so that all form responses are stored at the same location.

In such situations, Google Forms can be an easier option. It is easy to share, mobile friendly, and gets the job done. All responses are stored in your Google Drive, and you can even add collaborators to work on the form responses.

How to Embed a Google Form in WordPress

First you need to visit the Google Forms website. If you haven’t already created a form, then select a template to start a new form.

Creating a new form in Google Forms

Creating a new form in Google Forms is quite simple. First you need to provide a form title, description, and then you can start adding your form fields.

Google’s AI technology automatically selects the correct form field based on the question you ask. If it selects incorrect field type, then you can manually select it.

Adding form fields in Google Forms

You can click on the add button in the menu to add a new form field. You can also add images and videos.

Once you are satisfied with your form, click on the send button to get the embed code.

Get form embed code

This will bring up the send form popup where you need to click on the embed tab. Next, click on the ‘Copy’ link to copy the embed code.

Copy your Google Forms embed code

After that head over to your WordPress site’s admin area and edit the post or page where you want to display the form.

On the post edit screen, you will need to switch to the text editor and then paste your form code.

Paste Google Forms embed code in WordPress post

Don’t forget to click on the save or publish button to save your changes.

You can now preview your post or page to see the Google form embedded in WordPress.

A Google Form embedded in a WordPress page

We hope this article helped you learn how to easily embed Google Forms in WordPress posts and pages. You may also want to see our list of 19+ free Google tools every WordPress bloggers should use.

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 Embed a Google Form in WordPress appeared first on WPBeginner.

How WordPress Actually Works Behind the Scenes (Infographic)

Have you ever wondered how WordPress actually works behind the scenes? For most users, it seems simple because you type a URL and a page loads in few seconds, but there is a lot that happens behind the scenes. In this guide, we will walk… Read More »

The post How WordPress Actually Works Behind the Scenes (Infographic) appeared first on WPBeginner.

Have you ever wondered how WordPress actually works behind the scenes? For most users, it seems simple because you type a URL and a page loads in few seconds, but there is a lot that happens behind the scenes. In this guide, we will walk you through how WordPress actually works behind the scenes, and we have created an easy to follow infographic as well.

How WordPress Works Behind the Scenes

Why You Should Learn How WordPress Works?

WordPress is an open source software, which means any one can study its code and write their own apps (plugins) and templates (themes) for it.

Learning how WordPress works and what goes on behind the scenes can help you understand what you can do with it. You can learn about improving WordPress performance and write better code for your own projects.

This guide will walk you through the whole process step by step. We will start from when a user requests a page and end when that page is fully loaded.

Ready? Let’s get started.

Click to View the Behind the Scenes WordPress Infographic

You can also follow our written tutorial below for more details.

1. Load wp-config.php File

The wp-config.php is the WordPress configuration file. It sets global variables for a WordPress site and contains your WordPress database information. This is the first file WordPress loads for obvious reasons. Learn more about wp-config.php file and how to edit it.

2. Setup Default Constants

After loading wp-config.php file, WordPress will move on to set default constants. This includes information like default WordPress upload location, maximum file sizes, and other default constants set in wp-config.php file.

3. Load advanced-cache.php File

If advanced-cache.php file exists on your site, then WordPress will load it next. This file acts as a drop-in file and is used by several popular plugins particularly WordPress caching plugins. If your site is using this file, then you will see a new item on the plugins screen called Drop-ins.

advanced-cache.php file appearing as drop-in

4. Load wp-content/db.php File

WordPress allows developers to create their own database abstraction layers and load them in a db.php file placed inside the wp-content folder. It is commonly used by WordPress caching plugins to improve database performance. If your website has this file present, then WordPress will load it.

5. Connect MySQL and Select Database

WordPress now have enough information to proceed further. It will move on to connect to the MySQL server and select the database.

If WordPress is unable to connect to the database, then you will see the “Error establishing database connection” error and WordPress will quit right here.

If everything works fine, then it will move on to next steps.

6. Load object-cache.php or wp-includes/cache.php File

WordPress will now look for object-cache.php file. If it doesn’t exist, then WordPress will move on to load wp-includes/cache.php file.

7. Load wp-content/sunrise.php File

If it is a multisite network, then WordPress will now look for sunrise.php file if it exists in the wp-content folder.

8. Load Localization Library

WordPress will now load l10n.php library in the wp-includes folder. This file loads WordPress localization system, loads translations, sets locales, etc. See our guide on how to use WordPress in other languages.

9. Load Multisite Plugins

If it is a multisite network, then WordPress will now load the multisite plugins. Learn more about how plugins work on WordPress multisite network.

Network activated plugins

10. Do Action ‘muplugins_loaded’

The action muplugins_loaded is now run by WordPress. This action is available only to network activated plugins on a WordPress multisite.

11. Load Active Plugins

WordPress will now load all active plugins on the site. It does that by looking in the active_plugins entry in the options table of your WordPress database. This allows WordPress to ignore plugins that are installed on your site but not activated.

12. Load pluggable.php File

The pluggable.php file contains functions that can be redefined by WordPress plugins. WordPress will now see if the functions inside this file are already defined by another plugin. Otherwise, it will define those functions itself.

13. Do Action ‘plugins_loaded’

WordPress will now run the action ‘plugins_loaded’. It allows developers to hook their functions to run after all active plugins have been loaded.

14. Load Rewrite Rules

WordPress will now load the rewrite rules. These rewrite rules help WordPress use SEO friendly URLs.

15. Instantiate $wp_query, $wp_rewrite, $wp

At this point WordPress loads the following objects:

$wp_query: The global instance that holds WP_Query class. It tells WordPress what content is requested in a typical WordPress query format.

$wp_rewrite: The global instance that holds your WP_Rewrite class. It contains your rewrite rules and functions which tell WordPress which URL to use to display the requested content.

$wp: The global instance of the WP class which contains functions that will parse your request and perform the main query.

16. Do Action ‘setup_theme’

WordPress will now move on to run ‘setup_theme’ action. This action runs before your WordPress theme is loaded.

17. Load Child Theme’s functions.php File

The functions.php file acts as plugin and is used in WordPress themes to add theme specific features to your website. If you are using a child theme, then WordPress will now load your child theme’s functions.php file.

Otherwise, it will go on and load your current active theme’s functions.php file.

18. Load Parent Theme’s functions.php File

If you are using a child theme, then WordPress will now load your parent theme’s functions.php file.

19. Do Action ‘after_setup_theme’

This action runs after WordPress has setup the theme and loaded theme functions. It is the first action available to themes.

20. Setup Current User Object

At this point, WordPress loads the current user object. It allows WordPress to manage the request in accordance with the user’s role and capabilities.

21. Do Action ‘init’

WordPress has so far loaded all the crucial information it needs. Now it fires the ‘init’ action.

This action allows developers to add code that needs to be executed after WordPress has loaded all previously mentioned information.

22. Do Action ‘widget_init’

The widget_init action allows developers to register widgets and run code they needed to run at this time.

23. Run wp()

WordPress now calls wp() function which is located in wp-includes/functions.php file. It sets up the WordPress query globals $wp, $wp_query, $wp_the_query and then calls $wp->main.

24. Parse Request

Now WordPress has all the information it needs to parse the user request. It starts by checking the rewrite rules to match the user’s request.

And then runs query variable filters, request action hook, and sends header request.

25. Run Query

If no content matches the query, then WordPress will set is_404 variable.

Otherwise, WordPress will go on to load query variables.

It will then run WP_Query->get_posts().

Next, it fires DO_ACTION_REF_ARRAY ‘pre_get_posts’ action with WP_Query object.

WordPress will now run apply_filters to clean up query and run some final checks.

Now it fetches posts from the database and applies posts_results and the_posts filters.

The query part ends with WordPress returning the posts.

26. Do Action ‘template_redirect’

WordPress will now run the template_redirect action. This hook runs just before WordPress determines which template page to load.

27. Load Feed Template

If the requested content is a RSS feed, then WordPress loads the feed template.

28. Load Template

WordPress will now look for the template file based on WordPress template hierarchy. It then loads the template which usually contains a WordPress loop.

29. Do Action ‘shutdown’

Just before ending all PHP execution, WordPress fires the last action called shutdown.

WordPress stops working here. It has run the code and generated user’s requested web page.

Now, your web hosting server replies to user’s request by sending them the web page generated by WordPress. This page contains HTML, CSS, and Javascript code, which tells user’s browser how to display it on screen.

Amazing isn’t it? All these things happen within milliseconds. If you are using one of these best WordPress hosting services, then ideally your page will load in a couple of seconds.

We hope this article helped you learn how WordPress works behind the scenes. You may also want to see our step by step guide on how to boost WordPress speed and performance for beginners.

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 WordPress Actually Works Behind the Scenes (Infographic) appeared first on WPBeginner.