Expert Group of programming
Loading...

Mastering the post_class() Function

Posted by : Heycode Tech | Posted in : wordpress, WordPress Functions | Oct 25,2015 | 1 comments

The function named : post_class() :is one of the many functions provided by the WordPress for using the theme development. As the name, You can easily understand that it will add the class attribute with the value of post information.
logo-fotor
Here is the correct way for using this function :-

Type 1 : 
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?> > 

Type 2 :
<div id="post-<?php the_ID(); ?>" < ?php post_class( 'class-name' ); ? > >

Here is the output :

<div id="post-4564" class="post post-4564 category-48 category-dancing logged-in">

As per output, you can understand that attribute :class : is not used in function. This attribute have been added by the function automatically.

Filter/customize this function

Sometimes, we need to customize or add more classes as per requirement in function : post_class() : then it is also available. WordPress have provide the filter functionality for customize this class functionality.
Let’s see it.

function heycodetech_post_classes( $classes, $class, $post_id ) {
  global $post;
if(isset($post)){
     $classes[] = $post->post_title;
  } 
    return $classes;
}
add_filter( 'post_class', 'heycodetech_post_classes', 10, 3 );

By using of this filter, you can add number of custom classes as per requirement. Now you can unset the any class of this function also.

Conclusion

As we have seen post_class() is a very useful function and it will make styling your themes a lot easier if used properly. If you’ve got any questions, let me know in the comments.

Note : As per post class, wordpress have one more function which is very similar to this,named as : body_class() : .

Tags:

Author information - Heycode Tech

Every world can ask question and my website registered user give the suggestion.

See all posts by Author

Connect to author

About us

Heycodetech is a platform where you can ask any questions related to the programming like PHP,jQuery, MYSQL,HTML , CSS and moreHere is the Expert group of programming.