If you want to add an ancestor CSS class to posts in WordPress, it’s easy to do. This article will explain the basic steps and helpful tips for using ancestor classes in WordPress.
First, we’ll explain how to add an ancestor CSS class to posts. Then, we’ll provide tips to help you get the most out of your style changes.
Add this code to your WordPress theme’s functions.php file:
<?php
// Add an Ancestor Class to single posts
add_filter('body_class','single_ancestor_class');
function single_ancestor_class( $classes ) {
// If this is a single post
if ( is_single() ) {
// Get its post ancestors
$post_ancestors = get_post_ancestors( get_the_ID() );
// If the post has ancestors
if ( $post_ancestors ) {
// Get the first ancestor's ID
$post_ancestor_id = $post_ancestors[0];
// Add a class with the ancestor's name
$classes[] = 'ancestor-'.get_post($post_ancestor_id)->post_name;
}
}
// Return the modified classes array
return $classes;
}
?>
This function will add a custom class to the body element of single posts in the format ancestor-[ancestor-name]
, where [ancestor-name]
is the name of the first ancestor of the post.
This WordPress function adds a custom class to the body element of single posts based on the post’s ancestors. It:
- Adds a filter to the
body_class
hook, which calls thesingle_ancestor_class()
function whenever the body class is generated, adding the custom class to single posts. - Checks if the current page is a single post using the
is_single()
function. - Retrieves the post’s ancestors using the
get_post_ancestors()
function and stores them in the$post_ancestors
variable. - Gets the first ancestor’s ID using the
$post_ancestors[0]
array index and stores it in the$post_ancestor_id
variable. - Adds a class to the
$classes
array with the name of the ancestor, using theget_post()
function to retrieve the ancestor’s post object and thepost_name
property to get the ancestor’s name. - Returns the modified
$classes
array.