wordpress add field to post_class

I need to add a custom field to my article post but not sure how to add an additional class to it.

Currently the classes get pulled through like this <?php post_class($classes); ?>.

Read More

However I need to add a custom field to this as well. To demonstrate ive added a class= but this doesnt work as class= is being added twice.

<?php post_class($classes); ?> class="<?php the_field( "size" ); ?>

So i need post_class and the_field to work together.

Related posts

Leave a Reply

3 comments

  1. You can do this with two different way,

    First:- Add following code in theme's functions.php file:

    This will add your class where post_class is called.

    function category_id_class($classes)
    {
        global $post;
        if($post->post_type == 'post')
        {
            $classes[] = get_field( "size" );;
        }
        return $classes;
    }
    add_filter('post_class', 'category_id_class');
    

    Second:- Add this following code directly into your page:-

    $post_classes = get_post_class();
    $post_classes= implode(' ', $post_classes);
    echo 'class="'.$post_classes. the_field( "size" )'"';
    

    Hope this will help you little bit.

  2. So why you could not do like this:

    <?php post_class(the_field( "size" )); ?>
    

    Because it is working like this:

    <?php post_class('my_custom_class'); ?>