2

I've been using the code below to count items in a directory and then, by using a plugin, add it to a WordPress page.

$dir = '/PATH TO DIRECTORY/';
$filecount = 0;
$d = dir($dir);
while ($f = $d->read()) {
 if(($f!= ".") && ($f!= "..")) {
 if(!is_dir($f)) $filecount++;
 }
}
echo '(',$filecount,')';

Wondering whether I can make a shortcode from it, I've pre-pended it with

function item_count() {

And appended it with:

}
add_shortcode('count', 'item_count');

But the echo is triggering a 'headers already sent' error.

I've since learned that shortcodes should 'return' rather than 'echo', but haven't been able to figure-out what I need to do to use this as a shortcode.

1 Answer 1

2

It should be as simple as this:

function item_count() {
    $dir = '/PATH TO DIRECTORY/';
    $filecount = 0;
    $d = dir( $dir );
    while ( $f = $d->read() ) {
        if ( ( $f!= "." ) && ( $f!= ".." ) ) {
            if( ! is_dir( $f ) ) {
                $filecount++;
            }
        }
    }
    return '(' . $filecount . ')';
}

add_shortcode( 'count', 'item_count' );

If that's still giving you a Headers Already Sent error, then check to make sure that there's no whitespace at the end of your PHP file. (You can safely omit the closing ?> tag, which will help you ensure that there's not any extraneous whitespace.)

See this answer for more on omitting the closing PHP tag.

2
  • Thanks. That's excellent. Appreciated. I'd tried using 'return' but got the periods and quotes wrong. Commented Oct 5, 2016 at 15:12
  • Here's a Q & A about , vs. . / echo vs. return. Commented Oct 5, 2016 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.