2

I am working on a foreach loop in Wordpress and want to add 'post_class()' to a div within it. Currently the code looks like this:

if ( is_array( $posts ) && !empty( $posts ) ) {

    echo '<ul class="tribe-related-events tribe-clearfix hfeed vcalendar">';
    foreach ( $posts as $post ) {
        echo '<li>';
            echo '<div class="overlay">';
                echo   '<div '. post_class() .'>'; 
                echo        '<h3>'. tribe_get_event_taxonomy() .'</h3>';
                echo    '</div>';
            echo '</div>';
        echo '</li>';
    }
    echo '</ul>';
}

The 'post_class()' function is breaking the div it is in and calling the classes as if they were content in the page.

Any ideas?

4

The solution has actually been less complicated than I initially thought. The post_class() function does not return a string, but instead it "echoes" the string. Therefore, when you write.

echo '<div ' . post_class() . '>'; 

The effect is the following:

First, the system execute post_class(), generating an "echo ...." with the class attribute second, the system makes the requested concatenation and echoes the text "".

The right way to use it is:

echo "<div ";
post_class();
echo ">";

or else:

echo '<div class="'. join( ' ', get_post_class() ) .'">';
  • Thanks for a perfect answer to your own question. I prefer the join() method since it makes the markup really obvious. – Matt Cromwell Mar 24 '16 at 2:00
  • It looks like @kaiser got there first with a similar answer and so probably deserves the accepted answer. – Phill Healey Aug 1 '17 at 20:29
3

The post_class() function just is a wrapper for get_post_class().

Keep in mind that the latter does not echo, but returns an Array so you have to do something like what post_class() does:

$classes = join( '  ', get_post_class() );

Your code (could) would look like the following. I changed the if check as well to first check if $posts is empty and then check if it is an array - which is more fail safe.

if (
    ! empty( $posts )
    AND is_array( $posts )
    )
{
    $items = array();
    foreach ( $posts as $post )
        $items[] = sprintf(
            '<li><div class="overlay"><div class="%s"></div><h3>%s</h3></div></div></li>',
            join( '  ', post_class() ),
            tribe_get_event_taxonomy()
        );

    ! empty( $items ) AND printf(
        '<ul class="tribe-related-events tribe-clearfix hfeed vcalendar">%s</ul>',
        join( '', $items )
    );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.