why post_class() function apply css classes to all other files?

I use the post_class() function to add a custom class of CSS like width and display property. But it applied to all other files like the about page, contact page. I tried to use the WordPress class instead of using the class attribute of HTML. I have referred wordpress.org. I thought post_class can use for WordPress predefined class and also for adding custom classes. It’s a right or wrong method. Please suggest if anyone knows, where to use the post_class()? and it is ok to use post_class() for adding custom classes.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

where to use the post_class()

You can use it pretty much everywhere (in WordPress), e.g. single post pages (single.php, single-my_cpt.php, etc.), search results pages (search.php), the index template (index.php), a template part (e.g. content.php), and a shortcode function.

it is ok to use post_class() for adding custom classes?

Yes, it is. post_class() is not restricted to WordPress default classes only.

So for example, post_class( 'my-class' ) will work unless if a code filters the classes and then removes the my-class from the list.

it applied to all other files like the about page, contact page

Restricting it (your custom CSS class) to be applied only to certain pages is your task and WordPress won’t automatically apply the restriction for you.

But WordPress provides various conditional tags like is_page() that you can use to add a CSS class only on certain pages, hence just use the relevant conditional tag with post_class().

For example, to add my-class only on a Page (post of the page type) with the slug about:

<div <?php post_class( is_page( 'about' ) ? 'my-class' : '' ); ?>>
    your code
</div>

<!-- or maybe like so: -->
<?php
// foo-bar would always be in the list
$classes = [ 'foo-bar' ];

if ( is_page( 'about' ) ) {
    $classes[] = 'my-class';
}
?>
<div <?php post_class( $classes ); ?>>
    your code
</div>

And note that post_class() by default uses the current post in the current WordPress query, i.e. the post referenced to by the global $post variable, so if you want to output the classes for a specific post, pass the post ID (or object) to post_class():

// 123 (2nd parameter for post_class()) is the post ID
<div <?php post_class( 'my-custom-class', 123 ); ?>>
    your code
</div>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x