WordPress Body Class 101: Tips and Tricks for Theme Designers

Are you an aspiring WordPress theme designer looking for new ways to use CSS into your themes?

Luckily, WordPress automatically adds CSS classes that you can utilize in your themes. Several of these CSS classes are automatically added to the <body> section of every page on a WordPress site.

In this article, we will explain the WordPress body class with tips and tricks for aspiring theme designers to utilize them in their projects.

Using WordPress body class for theme development
Here is a quick overview of what you’ll learn in this article.

What is WordPress Body Class?

Body class (body_class) is a WordPress function that allows you to assign CSS classes to the body element.

The HTML body tag normally begins in a theme’s header.php file, which loads on every page. This allows you to dynamically figure out which page a user is viewing and then add the CSS classes accordingly.

Normally most starter themes and frameworks already include the body class function inside the HTML body tag. However, if your theme does not have it, then you can add it by modifying the body tag like this:

<body <?php body_class($class); ?>>

Depending on the type of page being displayed, WordPress automatically adds the appropriate classes.

For example, if you are on an archive page, WordPress will automatically add archive class to the body element. It does that for just about every page.

Related: See how WordPress works behind the scenes (infographic)

Here are some examples of common classes that WordPress might add, depending on which page is being displayed:

.rtl {}
.home {}
.blog {}
.archive {}
.date {}
.search {}
.paged {}
.attachment {}
.error404 {}
.single postid-(id) {}
.attachmentid-(id) {}
.attachment-(mime-type) {}
.author {}
.author-(user_nicename) {}
.category {}
.category-(slug) {}
.tag {}
.tag-(slug) {}
.page-parent {}
.page-child parent-pageid-(id) {}
.page-template page-template-(template file name) {}
.search-results {}
.search-no-results {}
.logged-in {}
.paged-(page number) {}
.single-paged-(page number) {}
.page-paged-(page number) {}
.category-paged-(page number) {}
.tag-paged-(page number) {}
.date-paged-(page number) {}
.author-paged-(page number) {}
.search-paged-(page number) {}

As you can see, by having such a powerful resource at hand, you can entirely customize your WordPress page by using just CSS. You can customize specific author profile pages, date-based archives, etc.

That being said, now let’s take a look at how and when would you use the body class.

When to use The WordPress Body Class

First, you need to make sure that your theme’s body element contains the body class function as shown above. If it does, then it will automatically include all the WordPress generated CSS classes mentioned above.

After that, you will also be able to add your own custom CSS classes to the body element. You can add these classes whenever you need them.

For example, if you want to change the appearance of articles by a specific author filed under a specific category.

How to Add Custom Body Classes

WordPress has a filter that you can utilize to add custom body classes when needed. We will show you how to add a body class using the filter before showing you the specific use case scenario just so everyone can be on the same page.

Because body classes are theme specific, you would need to add the following code to your theme’s functions.php file.

function my_class_names($classes) {
	// add 'class-name' to the $classes array
	$classes[] = 'wpb-class';
	// return the $classes array
	return $classes;
}

//Now add test class to the filter
add_filter('body_class','my_class_names');

The above code will add a class “wpb-class” to the body tag on every page on your website. That’s not so bad, right?

Now you can utilize this CSS class in your theme’s stylesheet directly. If you are working on your own website, then you can also add the CSS using the custom CSS feature in theme customizer.

Adding custom CSS in theme customizer

Adding Body Class Using a WordPress Plugin

If you are not working on a client project and don’t want to write code, then this method would be easier for you.

The first thing you need to do is install and activate the Custom Body Class plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, you need to visit Settings » Custom Body Class page. From here you can configure plugin settings.

Custom Body Class settings

You can select post types where you want to enable body class feature and who can access it. Don’t forget to click on the save changes button to store your settings.

Next, you can head over to edit any post or page on your WordPress site. On the post edit screen, you will find a new meta box in the right column labeled ‘Post Classes’.

Adding body classes to a post in WordPress

Click to add your custom CSS classes. You can add multiple classes separated by a space.

Once you are done, you can simply save or publish your post. The plugin will now add your custom CSS classes to the body class for that particular post or page.

Using Conditional Tags with The Body Class

The real power of the body_class function comes when it is used with the conditional tags.

These conditional tags are true or false data types that check if a condition is true or false in WordPress. For example, the conditional tag is_home checks if the page currently displayed is the homepage or not.

This allows theme developers to check if a condition is true or false before adding a custom CSS class to the body_class function.

Let’s take a look at some examples of using conditional tags to add custom classes to the body class.

Let’s say you want to style your homepage differently for logged in users with the author user role. While WordPress automatically generates a .home and .logged-in class, it does not detect the user role or add it as a class.

Now, this is a scenario where you can use the conditional tags with some custom code to dynamically add a custom class to the body class.

To achieve this you will add the following code to your theme’s functions.php file.

function wpb_loggedin_user_role_class($classes) { 

// let's check if it is homepage
if ( is_home() ) {

// Now let's check if the logged in user has author user role.  
$user = wp_get_current_user();
if ( in_array( 'author', (array) $user->roles ) ) {
    //The user has the "author" role
    // Add user role to the body class
    $classes[] = 'author';
    // Return the classes array
    return $classes;      
} 
} else { 
// if it is not homepage, then just return default classes
return $classes; 
}
} 

add_filter('body_class', 'wpb_loggedin_user_role_class');

Now, let’s take a look at another useful example. This time we are going to check if the page displayed is a preview of a WordPress draft.

To do that we will use the conditional tag is_preview and then add our custom CSS class.

function add_preview_class($classes) { 
if ( is_preview() )  {
$classes[] = 'preview-mode';
return $classes;
}
return $classes; 
}
add_filter('body_class','add_preview_class');

Now, we will add the following CSS to our theme’s stylesheet to utilize the new custom CSS class we just added.

.preview-mode .site-header:before { 
content:'preview mode';
color:#FFF;
background-color:#ff0000;
}

This is how it looked on our demo site:

Custom preview mode CSS class added to the body class

You may want to check out the full list of conditional tags that you can use in WordPress. This will give you a handy set of ready to use tags for your code.

Other Examples of Dynamically Adding Custom Body Classes

Apart from conditional tags, you can also use other techniques to fetch information from the WordPress database and create custom CSS classes for the body class.

Adding category names to the body class of a single post page

Let’s say you want to customize the appearance of single posts based on the category they are filed in. You can use the body class to achieve this

First, you need to add category names as CSS class on single post pages. To do that, add the following code to your theme’s functions.php file:

// add category nicenames in body class
function category_id_class($classes) {
    global $post;
    foreach((get_the_category($post->ID)) as $category)
        $classes[] = $category->category_nicename;
    return $classes;
}
 
add_filter('body_class', 'category_id_class');

The code above will add the category class in your body class for single post pages. You can then use CSS classes to style it as you wish.

Adding page slug to the body class

Paste the following code in your theme’s functions.php file:

//Page Slug Body Class
function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );

Browser Detection and Browser Specific Body Classes

Sometimes you may come across issues where your theme may need additional CSS for a particular browser.

Now the good news is that WordPress automatically detects browser upon loading and then temporary stores this information as a global variable.

You just need to check if WordPress detected a specific browser and then add it as a custom CSS class.

Simply, copy and paste the following code in your theme’s functions.php file:


function wpb_browser_body_class($classes) { 
	global $is_iphone, $is_chrome, $is_safari, $is_NS4, $is_opera, $is_macIE, $is_winIE, $is_gecko, $is_lynx, $is_IE, $is_edge;

if ($is_iphone)    $classes[] ='iphone-safari';
elseif ($is_chrome)    $classes[] ='google-chrome';
elseif ($is_safari)    $classes[] ='safari';
elseif ($is_NS4)    $classes[] ='netscape';
elseif ($is_opera)    $classes[] ='opera';
elseif ($is_macIE)    $classes[] ='mac-ie';
elseif ($is_winIE)    $classes[] ='windows-ie';
elseif ($is_gecko)    $classes[] ='firefox';
elseif ($is_lynx)    $classes[] ='lynx';
elseif ($is_IE)      $classes[] ='internet-explorer';
elseif ($is_edge)    $classes[] ='ms-edge';
else $classes[] = 'unknown';
	
return $classes;
}
add_filter('body_class','wpb_browser_body_class');

You can then use classes like:

.ms-edge .navigation {some item goes here}

If it is a small padding or margin issue, then this is a fairly easy way of fixing it.

There are definitely many more scenarios where using the body_class function can save you from writing lengthy lines of code. For example, if you are using a theme framework like Genesis, then you can use it to add custom classes in your child theme.

You can use the body_class function to add CSS classes for full-width page layouts, sidebar content, header and footers, etc.

We hope this article helped you learn how to use the WordPress body class in your themes. You may also want to see our article on how to style each WordPress post differently, and our comparison of best WordPress page builder plugins.

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

The post WordPress Body Class 101: Tips and Tricks for Theme Designers appeared first on WPBeginner.

The Complete Social Media Cheat Sheet for WordPress (Updated)

Are you looking for a social media cheat sheet that you can follow to quickly set up social media profiles the right way?

If you are serious about your website or blog, then you simply can’t ignore social media. The problem is that each of these platforms has different requirements for cover photos, profile images, article covers, etc. This makes it quite overwhelming for new users to get started.

In this article, we will share our ultimate social media cheat sheet for WordPress.

The Complete Social Media Cheat Sheet for WordPress

Why Do You Need a Social Media Cheat Sheet for WordPress?

If you have been running social media profiles for your WordPress blog or website, then you would notice that each platform has different requirements.

For example, Facebook has specific requirements for image sizes while Pinterest needs totally different proportions.

It can be difficult to remember all that information when creating social media images for your articles or profile.

A cheat sheet helps you quickly look up all these options. It will also ensure that you don’t miss anything important when creating a social media profile or publishing a new article on your WordPress website.

That being said, let’s get started with our ultimate social media cheat sheet for WordPress users.

Here is a quick overview of the things we will cover in this article:

Choose Your Social Media Platforms

There are so many social media websites, but not all of them are helpful in growing your business or bringing traffic to your website.

Apart from bigger sites like Facebook and Twitter, you can choose platforms that work best with your website’s target audience and niche.

For example, if you run a fashion blog, then you may want to use Instagram to promote your content.

A food and recipe blog may want to focus on YouTube and Yummly.

Home decor or DIY websites may find Pinterest helpful in finding the right audience.

Choosing the right platforms for your target audience will help you create an effective social media marketing strategy to grow your business.

Social Media Image Sizes Checklist

To promote your blog or business on social media, you will need to setup profiles, upload your website logo and a cover photo, and create images to accompany your articles and links.

You can see our article on how to easily create images for your WordPress blog to learn how to make beautiful images without hiring a graphic designer.

Now the problem is that each social media platform has specific requirements for these images. Not using the right size would make your images look skewed or stretched.

Here is our quick cheat sheet for social media image sizes that you can use when creating images for your social accounts.

Facebook Image Sizes

Facebook page preview

Facebook has specific recommendations for images to be used in different areas.

Cover image: 820 x 312 pixels on computers and 640 x 360 pixels for smartphones. Cover images should be less than 100 KB in filesize. It could be in JPEG or PNG file format. You can create a larger image while maintaining the same aspect ratio, and Facebook will automatically create smaller sizes to display on mobile devices.

Profile image: An square image of at least 170 x 170 pixels on computers and 128 x 128 pixels on smartphones. For business pages, this is where you would ideally display your custom logo. This image will be cropped to display as a circle.

Shared Image: 1200 x 630 pixels. This image will be displayed on your page with a maximum width of 470 pixels and in the feed maximum width of 600 pixels.

Group cover image: 1640 x 856 pixels.

Twitter Image Sizes

Twitter preview

Twitter is the internet’s conversation hub. Following are the recommended image sizes for Twitter to make your profile more engaging and professional.

Header image: 1500 x 500 pixels. This full-width image appears as the cover image of your Twitter profile page.

Profile image: 400 x 400 pixels. This square image is cropped to be displayed in a circular format. Twitter allows you to upload JPG, PNG, and GIF formats with a maximum file size of 2MB.

In-stream image: 1200 x 675 pixels. This image is displayed when you share an article, retweet, embed a tweet, upload images, and more. If you are already using Twitter Cards then Twitter will be able to pick the correct image to display with your article description and title.

Instagram Image Sizes

Instagram preview

Instagram’s main content is already in a visual format. If you are uploading photos directly from your phone using the Instagram app, then it will automatically take care of appropriate image sizes for you.

For other uploads, you can follow these Instagram image size recommendations for the best results.

Profile image: 320 x 320 pixels. You can use larger image dimensions as long as it is a square image.

Image thumbnail: 161 x 161 pixels. This image is displayed as your thumbnails for your photos.

Shared photos: 1080 x 1080 pixels. You can use a higher resolution image as long as it is a square image.

Shared videos: 1080 pixels wide.

Instagram Stories: 1080 x 1920 pixels or minimum 600 x 1067 pixels. File size cannot exceed more than 4 GB which is quite a lot for a high-quality video.

YouTube Image Sizes

YouTube channel preview

YouTube is not only the second most popular social media platform but also the second most popular search engine. Your YouTube channel image, cover image, and video thumbnails are crucial in getting more views for your videos.

YouTube Channel cover image: 2048 x 1152 pixels. You need to make sure that the image is horizontally centered so that it looks good on mobile devices where YouTube may crop the image to fit the user’s screen size.

Channel icon: 800 x 800 pixels. This image is displayed as your channel icon and may sometimes be cropped as a circular image.

Video thumbnail: 1280 x 720 pixels. Ask any YouTube creator and they will tell you that the video thumbnail is the most important part of video optimization on YouTube. This is what YouTube users will see on their homepage, in search, and in other areas. A highly optimized video thumbnail helps you get more views and grow your channel.

Pinterest Image Sizes

Pinterest preview

Pinterest is a visual social sharing platform, which means images play the most significant role in growing your Pinterest following.

Profile image: 165 x 165 pixels. You can upload a higher resolution image with a maximum file size of 10 MB.

Profile cover: 800 x 450 pixels. Select a board to feature as your profile’s cover. Pinterest will automatically fetch pins from that board to create your profile cover.

Board cover image: 222 x 150 pixels. Pinterest allows you to choose the cover image from the pins you have saved for that board.

Pinned image preview: 236 pixels wide. Pinterest automatically scales your pins to fit their grid. For best results, you need to upload the images with an aspect ratio of 2:3 to 1:3.5.

LinkedIn Image Sizes

LinkedIn preview

LinkedIn can be a great source of traffic, connections, and building a brand image. It is a social networking platform for professionals and businesses, which makes it a powerful tool to help you grow your business.

Personal profile image: 400 x 400 pixels with a maximum image file size of 10 MB.

Banner image for personal profile: 1584 x 396 pixels with a maximum file size of 4 MB.

Company cover image: 1128 x 191 pixels.

Shared image: 1200 x 627 pixels.

Company profile / logo image: 300 x 300 pixels or higher resolution image with 1:1 aspect ratio.

Setting up Social Media Optimization in WordPress

Now that you have learned about proper social media image sizes, the next step is to make sure that your WordPress site is optimized for social media.

The most important aspect of this optimization is to set up automatic inclusion of Open Graph metadata. Open Graph metadata is a technology that allows you to include additional information to your web pages that social media and search engines need.

First, you need to install and activate the All in One SEO plugin. For more details, see our step-by-step guide on how to install a WordPress plugin.

AIOSEO is the best WordPress SEO plugin that helps you get more traffic from search engines. It is also a complete website optimization tool including support for social media platforms as well.

Upon activation, you need to visit All in One SEO » Social Networks page. From here, you need to first add your social media profile URLs under the ‘Social Profiles’ tab.

The AIOSEO SEO plugin for WordPress

You don’t need to add all URLs, you can simply skip the social media websites where you don’t have a profile.

Next, you need to switch to the Facebook tab. From here you can see that AIOSEO enables Open Graph metadata by default.

Upload default Facebook image

Below that you need to provide a default post Facebook image for your website’s front page. The image you provide here will be displayed when someone shares your website’s front page or root URL on Facebook.

Next, switch to the Twitter tab. Here you can choose the default card display for your website.

Add Twitter card details

A ‘summary with large image’ option will display your Twitter share image with a summary of your article.

You can now switch to the Pinterest tab. From here you can add the Pinterest confirmation tag to your website.

You can click on the link on the screen to claim your website and get the confirmation code. For more details, you can see our guide on how to verify your WordPress site on Pinterest.

Claim your Pinterest account

Don’t forget to click on the ‘Save Changes’ button to store your settings.

Social Media Settings for WordPress Posts and Pages

Just like the SEO settings for posts and pages, you can also optimize them for social media websites.

AIOSEO plugin allows you to easily set social options for your individual posts and pages.

Simply edit the blog post or page you want to optimize, and then scroll down to ‘AIOSEO Settings’ section below the editor.

Add social image in content editor

Switch to the ‘Social’ tab and you can upload a custom title and description as well as an image for Facebook and Twitter shares. You can also see a preview of what your post will look like when shared on social media.

After that, you can click on ‘Publish’ or ‘Update’ to save your post or page.

Adding Social Sharing Buttons to Your Website

The easiest way to promote your website on social media is by encouraging your users to share your content. This can be achieved by adding social sharing buttons to your blog posts and pages.

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

Shared Counts is the best social media plugin for WordPress. It allows you to easily add social sharing buttons to your WordPress blog posts.

Upon activation, simply head over to Settings » Shared Counts page to configure plugin options.

Share counts settings

From here you need to scroll down to the ‘Display’ section and select the social media websites you want to display in the ‘Share Buttons to Display’ field.

After that, you can choose a button style and location where you want to display the buttons.

Don’t forget to click on the ‘Save Changes’ button to store your settings.

You can now visit any post on your website to see social sharing buttons in action.

For more detailed instructions, see our guide on how to add social share buttons in WordPress.

Setting up Automated Social Sharing in WordPress

Social media platforms are great for building a following and bringing more traffic to your website. However, it can become quite time-consuming to share content across different platforms and engage with your audience.

Luckily, there are several online tools that you can use to automate the process.

We hope this social media cheat sheet for WordPress helped you improve your social media marketing strategy. You may also want to see our list of best email marketing services and how to start your own podcast.

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 The Complete Social Media Cheat Sheet for WordPress (Updated) first appeared on WPBeginner.