add css class or id before a wordpress post/page
-
21-12-2019 - |
Question
i'm building a wordpress plugin, but to my plugin work needed a specific class in to html code (javascript linkify), but all templates themes are using different classes to formating the posts, for example:
<div class="post_content">
or
<div class="content">
How i can embebed through my plugin my own specific div class to identify a post or page?
Solution
Checkout the Codex for body_class()
and post_class()
. If the theme supports it (and every well written theme should support it) you can add your own classes to the body or post.
function my_plugin_class($classes) {
if ( my_plugin_is_loaded() ) {
$classes[] = 'my-plugin-class';
}
return $classes;
}
add_filter('post_class', 'my_plugin_class'); // add the class to the post content
add_filter('body_class', 'my_plugin_class'); // add the class to the body tag
You can differ between pages and posts with is_page()
and is_single()
OTHER TIPS
Use the body class filter. This will add a class to the body element.
E.g.
function wpse_plugin_add_body_class( $classes ) {
if ( my_plugin_conditional() ) {
$classes[] = 'my-plugin-class';
}
return $classes;
}
add_filter( 'body_class', 'wpse_plugin_add_body_class' );
Be sure to change the conditional function to whatever you need. Then add your CSS like so:
.my-plugin-class #content {
color: #ff0000;
}