WordPress: Modifying the content function

is there a way to modify the the_content() function? I would like to add a css class when it display a custom taxonomy negative and positive taxonomy.

Example:

Read More
<p class="positive">this is a content for the positive taxonomy</p>
<p class="positive">this is a content for the positive taxonomy</p>
<p class="negative">this is a content for the negative taxonomy</p>

I would like to apply it in the author.php code:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
                  <?php the_content(); ?>
                <?php endwhile; else: ?>
                <p><?php _e('No posts by this author.'); ?></p>
              <?php endif; ?> 

with the function.php :

add_action( 'pre_get_posts', function ( $q ) {

    if( !is_admin() && $q->is_main_query() && $q->is_author() ) {

        $q->set( 'posts_per_page', 100 );
        $q->set( 'post_type', 'custom_feedback' );

    }

});

PS: I am using custom post type here with custom taxonomy with two category positive and negative.

Related posts

1 comment

  1. You can use has_term() to test whether or not a post has a certain term. Alternatvely, you can use get_the_terms to get the terms attached to a post and use the term slug as value in your css class. This is a bit unreliable if a post has more than one term attached to it

    SOLUTION 1

    <?php
        $class = '';
        if ( has_term( 'positive', 'custom_taxonomy' ) ) {
            $class = 'positive';
        } elseif ( has_term( 'negative', 'custom_taxonomy' ) ) {
            $class = 'negative';
        } 
    ?>
    
    <div class="entry-content ><?php echo $class ?>">
        <?php the_content(); ?>
    </div>
    

    SOLUTION 2

    <?php
    $terms = get_the_terms( $post->ID, 'custom_taxonomy' );
    $class = $terms ? $terms[0]->slug : 'normal';
    ?>
    
    <div class="entry-content ><?php echo $class ?>">
        <?php the_content(); ?>
    </div>
    

    USAGE

    You can now use your CSS selectors to target your content

    .entry-content positive {}
    .entry-content negative {}
    

Comments are closed.