Website Guider

The Ultimate Resource for WPadmins and Geeks

How To Add Custom Class To Specific Post in WordPress

Do you want to add a different class to a specific post or page. If yes, you have landed on the right place. In this short tutorial, I am going to show you how to add custom class to specific post or page in WordPress.

I will show you the code and how to use it. Remember you, this code snippet should placed in themes functions.php file. Let’s begin.

Why To Add Custom Class To Specific Post or Page

If you are a WordPress theme designer and you want to tweak the design of a specific post like 404 or home. And want to create styles for that post.

As you know, all the posts have same class. If you point the CSS to the specific post using the common post class, that may create design problems.

In that case, you need a specific class for specific post or page. How will you do it and what will you do if you don’t have any options in theme.

Well in that case, you can take help from the developer. But that will cost money.

When I began to create themes, I also faced these problems and now I solve problems. So I thought to write about it.

Without consuming more time let me show the code regarding custom post class in WordPress.

How To Add Custom Class To Specific Post in WordPress

You have to paste this code directly in your functions.php file.

add_filter( 'post_class', 'new_class');
function new_class (array $classes) {
$newclass = 'my_class';
if ( is_single('1390') ) {
$classes[] = esc_attr( $newclass );
}

return $classes;
}

You may ask What are you doing here. Well, I am targeting a post by using the id of the post which is 1390. Also, I am using WordPress add_filter function to do modification to the post.

I am creating a variable $newclass which holds the class name my_class. You have to change this my_class to the one you want.

But remember to put the class name inside the single or double quotes.

Also, if you want to apply class to page, you have to use is_page instead of is_single.

Wait Wait. What if you want to add the same class to many posts. You have to use array. Check the code below.

add_filter( 'post_class', 'new_class');
function new_class (array $classes) {
$newclass = 'my_class';
if ( is_single(array('1390', '1391') ) {
$classes[] = esc_attr( $newclass );
}

return $classes;
}

Here, I am targeting the two posts with the ids 1390 and 1391. If you want to add many other posts, follow the same procedure. Add post id inside the array inside single quotes followed with comma as done.

I hope you loved this short tutorial. If so please do share with your friends whom about you care or work with. Also, don’t forget to share and comment.

Raashid Din Dar

Raashid Din Dar is a web developer and designer. He specialises in WordPress Theme and Plugin development. Also, Web Designing is what he loves.He loves to read books and play with friends.

Leave a Reply

Your email address will not be published.

Back to top