Site logo

Archived topic

Add custom class to "site-content" and only for blogroll and archive pages

5 replies · Started by Alexander on July 10, 2022

Viewing posts 1–6 of 6

Hi, I need to add a custom class to "site-content" the specific line of html where the class is, is <div id="content" class="site-content">. I also need the custom class to only be applied to the blogroll and archive pages where posts load as columns, not to other pages such as single post pages.

I was having a look through the filters section and although I found the generate_content_class and generate_main_class filters, I couldn't find a filter that would apply to <div id="content" class="site-content">. It is possible I missed it though.

Also I'm a bit stuck with the PHP code. I'm pretty new to it so I was hoping I could get some help with the PHP code I would need to add the class via the filter and for it to only apply to the blogroll and archive pages.

Sorry to bother you with this, I've just got completely stuck :)

Thanks

Hi there,

no apologies necessary, luckily we have this filter hook in the Theme: generate_parse_attr

So you can do this:

add_filter( 'generate_parse_attr', function( $attributes, $context ) {
    if ( 'site-content' === $context && is_home() || is_archive() ) {
        $attributes['class'] .= ' your_class';
    }

    return $attributes;
}, 10, 2 );

To break it down:

if ( 'site-content' === $context && is_home() || is_archive() ) {

First we check the $context parameter of the filter for only the site-content element.
You can see a list of the other cases in the free theme here:

https://github.com/tomusborne/generatepress/blob/adfe090929b0515cdf894f4c6b722cfe8c0790dc/inc/class-html-attributes.php#L51-L118

We then check if its the home ( blog ) or archive templates.

And if so we can then append your_class to the $attributes['class'] array.

Just change your_class to your class - keep the leading space.

Thanks a lot, works perfectly and thanks for the github link.

Just to clarify, what do the numbers at the end mean }, 10, 2 );? I have seen this before, but just not entirely sure.

Thanks

Thank you

No problem :)

This archived topic is closed to new replies.