Tag Archives: Posts

Add the Post Category Name to the Single Post Body Class

Sometimes you want to use your wordpress site for advanced customization such-as assigning different styles to varying category posts.This is a less than a minute task, just copy and paste the following code into the active functions.php file for your theme and save.


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

Now, you’ll realize that for each single post’s body class another class has been added. For example if you have a category named “Alphasoft” then all single posts in this category have a class “Alphasoft” in their body class array.

It’s usage is very simple, body.alphasoft identifies such single/category post pages. Go crazy with your css.

Adding Google Ad or HTML in the middle of your posts

A quick safe way to automatically add your Google ad or any HTML just in the middle of your wordpress posts;

Simply add the following code to your theme’s function.php file then replace “HTML CODE” with your google ad code, that is it.


/* Content Google Ads */
add_filter( 'the_content', 'wpse_ad_content' );
function wpse_ad_content( $content ) {
if( !is_single() ) return $content;
$paragraphAfter = 3;
$content = explode ( "
", $content );
$new_content = '';
for ( $i = 0; $i < count ( $content ); $i ++ ) {
if ( $i == $paragraphAfter ) { $new_content .= 'HTML CONTENT'; }
$new_content .= $content[$i] . "";
}
return $new_content;
}

With this, your Google Ad or any other HTML will appear just after the specified number of paragraphs in your content. Notice the following;

  1. $paragraphAfter = 3;will display the ad after third paragraph.
  2. $new_content .= $content[$i] . ""; You can use this to insert a second HTML or Google Ad after paragraph 6 in the above case where first ad is after paragraph 3.
  3. If you are using a custom theme, be sure to locate the active functions.php file that the theme author set active otherwise the default is located just in the theme directory.

Enjoy