Search code examples
phppluralize

Pluralize text in function


I'm looking to be able to pluralize "Slide" in the below function:

// Changes the default download button text
function ps_download_button($args) {
    $download_text = 'Download ' . '(' . get_field('no_slides') . ' Slide)';
    $args['text'] = $download_text;
    return $args;
}
add_filter( 'edd_purchase_link_args', 'ps_download_button' );

This is my first stab at writing custom PHP functions. I've managed to find related code but I'm not sure how to integrate it with the above:

function plural( $amount, $singular = '', $plural = 's' ) {
    if ( $amount === 1 ) {
        return $singular;
    }
    return $plural;
}

Solution

  • Well you can use ternary for that.

    function ps_download_button($args) {
        $amount = intval(get_field('no_slides'));
        $download_text = 'Download ' . '(' . $amount . ') Slide'. (($amount>1)?'s':'');
        $args['text'] = $download_text;
        return $args;
    }
    

    That's the simplest way, and no need for a function. If you don't understand how ternary works, take a look at this question.