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.

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.

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.