skip to Main Content

This one has me stumped.

So, if we want to add a custom class to the body class, easy to create a filter like so.

/**
 * Body Class
 *
 */
function jm_custom_body_class( $classes ) {
    $classes[] = 'custom-class';
    return $classes;
}
add_filter( 'body_class', 'jm_custom_body_class' );

So how can I create my own custom filter for a site wide container like for example.

<div class="content-wrap">

And then somewhere else, perhaps a page template, I may want to add a row class to that hooking into it with a function to look like this.

<div class="content-wrap row">

or maybe

<div class="content-wrap full">

Depending on what I need

I’m guessing I can use apply_filters for this?

<div class="apply_filters('content-wrap' 'don't know how to this')">

Hope that make sense.

2

Answers


  1. Chosen as BEST ANSWER

    I came up with this to better demonstrate what I intended to do. The example below works but however it obviously 'replaces' the class, where I need it to add the additional class.

    In index.php

    echo '<main class="' . apply_filters( 'jm_content_area_wrap', 'content' ) . '" role="main">';
    

    Then say in a page template I can use this

    // Add .bg-primary class
    function jm_test_class( $test_class ) {
    
        $test_class = 'content bg-primary'; // This replaces the .original class, rather than adding to it, so I need to add .content back.
        return $test_class;
    
    }
    add_filter( 'jm_content_area_wrap', 'jm_test_class' );
    

  2. The apply_filters() function accepts (at minimum) two parameters: the hook’s name, and the value to be filtered. Additional parameters can be added after the first two to provide more arguments for the callback attaching to the filter.

    For your situation, I usually put the classes into a variable as an array, to make management a little bit easier:

    add_filter( 'jm_content_wrap_classes', static function ( $classes ): array {
        if ( ! is_array( $classes ) ) {
            $classes = [ 'content-wrap' ];
        }
    
        if ( condition() ) {
            $classes[] = 'row';
        }
    
        return $classes;
    } );
    
    ...
    
    $classes = apply_filters( 'jm_content_wrap_classes', [ 'content-wrap' ] );
    printf( '<div class="%s">', esc_attr( implode( ' ', $classes ) ) );
    

    Or filtering a string:

    add_filter( 'jm_content_wrap_classes', static function ( $classes ): string {
        if ( ! is_string( $classes ) ) {
            $classes = 'content-wrap';
        }
    
        if ( condition() ) {
            $classes .= ' row';
        }
    
        return $classes;
    } );
    
    ...
    
    $classes = apply_filters( 'jm_content_wrap_classes', 'content-wrap' );
    printf( '<div class="%s">', esc_attr( $classes ) );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search