4

I've created a shortcode for a sitemap page. When I make a change on the page and click update I get a headers already sent error. Below is my shortcode and the two error messages. I'm wondering if I need to work ob_start() and ob_get_clean() into my function but I'm not 100% positive how it should be formatted.

function site_map2( $atts ) {
    $atts = shortcode_atts(
        array(
            'exclude' => '',
        ), $atts );
        return '<ul>' . wp_list_pages('exclude=' . $atts['exclude'] . '&sort_column=post_title&title_li=') . '</ul>';
}
add_shortcode( 'SiteMap2', 'site_map2' );

Here are the error messages:

Warning: Cannot modify header information - headers already sent by (output started at /public_html/wp-includes/post-template.php:1205) in /public_html/wp-admin/post.php on line 197

Warning: Cannot modify header information - headers already sent by (output started at /public_html/wp-includes/post-template.php:1205) in /public_html/wp-includes/pluggable.php on line 1167

6

The adjustment to my function below fixed the issue but I wanted to make sure that this is the right way to handle the shortcode. I've added ob_start(); and ob_get_clean(); to the function. Is this the correct way to handle something like this?

function site_map2( $atts ) {
    $atts = shortcode_atts(
        array(
            'exclude' => '',
        ), $atts );
        ob_start();
        echo '<ul>' . wp_list_pages('echo=false' . '&exclude=' . $atts['exclude'] . '&sort_column=post_title&title_li=') . '</ul>';
        return ob_get_clean();
}
add_shortcode( 'SiteMap2', 'site_map2' );
  • Sure. If you have to output, ob_start() / ob_get_clean() are what I use often. – jgraup Aug 17 '16 at 4:12
2

You need to return the value from wp_list_pages and not 'echo' by default.

'echo'

(bool) Whether or not to echo the list of pages. Default true.

return '<ul>' . wp_list_pages( 'echo=false' . '&exclude=' . $atts['exclude'] . '&sort_column=post_title&title_li=') . '</ul>';
  • I implemented this into my functions file but I still get the same error. I click update and I'm taken to a page that display my site map but without my template and styles "mysite.com/wp-admin/post.php" with the error messages at the bottom of the page. It's very strange. – brandozz Aug 15 '16 at 2:48
  • 2
    either way you shouldn't echo output from the shortcode, only return the final string. – jgraup Aug 15 '16 at 2:53

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.