Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

comments_number() is quite useful: It takes the result of get_comments_number() and prepares the output with some localization magic. Unfortunately, it prints the result out when it is done, it doesn’t offer an option to just return the string.

How can I get the string without printing it? I want to use it as a variable value.

share|improve this question
add comment

2 Answers 2

up vote 1 down vote accepted

Easiest way:

ob_start();
comments_number();
$data = ob_get_clean();

$data will contain the text.

share|improve this answer
    
This was my first idea. I just don’t like ob_start(). But you are right, it should be rather safe in this situation. –  toscho Aug 25 '12 at 19:49
    
Marking this as answer because it is much more readable than my own solution. :) –  toscho Aug 26 '12 at 16:57
add comment

Create a wrapper function: filter the result of comments_number(), store it in your wrapper, and return an empty string to the native function. return the real string in your wrapper function.

/**
 * Wrapper for native comments_number().
 *
 * This has two functions:
 * 1. It is can be called from a theme or plugin to get the comments number
 *    string *returned* for a variable.
 * 2. It sets itself as a temorary filter to catch the string. The filter will
 *    be removed immediately afterwards.
 *
 * @wp-hook comments_number
 * @param   string $zero Template for no comments OR the parsed string
 *                       when used as filter.
 * @param   string $one
 * @param   string $more
 * @return  string
 */
function t5_get_comments_number( $zero = FALSE, $one = FALSE, $more = FALSE )
{
    static $output = '';

    if ( 'comments_number' === current_filter() )
    {
        remove_filter( current_filter(), __FUNCTION__ );
        $output = $zero;
        return '';
    }
    else
    {
        add_filter( 'comments_number', __FUNCTION__ );
        comments_number();
        return $output;
    }
}

Usage:

$comm_num = t5_get_comments_number();
print "We found $comm_num.";

// Prints for example: We found 51 Comments.
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.