Home > Software design >  Getting 'Headers already sent' error in loop with CPT and ACF
Getting 'Headers already sent' error in loop with CPT and ACF

Time:11-27

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 ><div ><h3>';
        the_title();
    echo    '</h3></div><div >';
        the_field("dato");
    echo    '</div></div>';
} 

CodePudding user response:

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 ><div ><h3>';
                the_title();
            echo    '</h3></div><div >';
                the_field("dato");
            echo    '</div></div>';
        $result = ob_get_clean();
    } else {
        $result = '';
    }
    return $result;
} 
  • Related