Good day,
Perhaps you are willing to help out a php-beginner.
I'm trying to add a post or page tag to the list of classes appearing in the body tag's class attribute. These classes are printed onto html by header.php:
<body <?php body_class(''); ?>>
In the past, I have successfully used the following code to print my page tag into a meta element:
<meta name="print-post-tag" content="<?php
$posttags = get_the_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo $tag->name;
}
}
?>
" >
Note: Posts have tags by default, but I use the Plugin "Tag Pages" to add tags to pages.
So now I'm trying to do something similar in the much used body attribute class space.
After reading the codex at http://codex.wordpress.org/Function_Reference/body_class and http://codex.wordpress.org/Function_Reference/the_tags , I found out that the best way to do this would be to add a Filter to my theme's functions.php.
My first attempt rendered nothing but errors: (multiple code errors here)
function the_tags( $classes ) {
global $tag;
foreach ( get_the_tags( $tag->name ) as $category ) {
$classes[] = $category->category_nicename;
}
return $classes;
}
add_filter( 'body_class', 'the_tags' );
Note: I am lacking a structural understanding of WordPress template structure and its many variables and functions.
2nd attempt: I tried executing Ryan's ( https://stackoverflow.com/questions/11232676/trying-to-add-the-slug-to-my-body-class-with-no-success-in-wordpress-can-anyone ) suggested solution, but my html isn't displaying the page tag. This is the attempt which I dropped at the bottom of my theme's functions.php:
function a_beautiful_new_body_class() { // adding a class to <body> tag
global $wp_query;
$tag = '';
if (is_front_page() ) {
$tag = 'home'; // 'home' as class for the home page
} elseif (is_page()) {
$tag = $wp_query->query_vars["tag"]; // placing the tag
}
if ($tag)
echo 'class= "'. $tag. '"';
}
How would you approach this problem?
Kindly,
<body <?php body_class('' . ' ' . $tag->name); ?>>
in header.php doesn't render the tag name either