How can I make a shortcode from this code?

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

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.

Leave a Comment