Search code examples
phploopsshortcode

Getting 'Headers already sent' error in loop with CPT and ACF


I've made a custom posttype and am using fields from ACF. I made this loop which works well on frontend.., but when sving a post in the CPT, it gives error: Headers alreday sent. Error refers to the line just below the if( $posts ) statement.

What can be wrong here?

add_shortcode("custom_acf", "event_loop_shortcode");
function event_loop_shortcode() {
$posts = get_posts(array(
    'posts_per_page' => -1,
    'post_type'      => 'event'
));
if( $posts ) 
    echo    '<div class="event"><div class="event_title"><h3>';
        the_title();
    echo    '</h3></div><div class="event_date">';
        the_field("dato");
    echo    '</div></div>';
} 

Solution

  • The shortcode function is supposed to return the contents rather than echo it. Also, I think you were missing braces for your if statement.

    add_shortcode("custom_acf", "event_loop_shortcode");
    function event_loop_shortcode() {
        $posts = get_posts(array(
            'posts_per_page' => -1,
            'post_type'      => 'event'
        ));
        if ( $posts ) { 
            ob_start();
                echo    '<div class="event"><div class="event_title"><h3>';
                    the_title();
                echo    '</h3></div><div class="event_date">';
                    the_field("dato");
                echo    '</div></div>';
            $result = ob_get_clean();
        } else {
            $result = '';
        }
        return $result;
    }