0

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;
}
Teege
  • 101
  • 6
  • `$pluralText = plural($originalText,$singularvalue,$pluralValue);` is the syntax to use the function you provided. The values which have `= somthing` in the function declaration line (top) are *optional*), so you can just as well write : `$pluralText = plural($originalText);` but you have the option of supplying specific information to the function. – Martin Jun 23 '16 at 11:31
  • it may bemore useful to you to replace the `===` with a double equals, `==` as that will still accept a string or float number as well as an integer. (on the `$amount === 1`) – Martin Jun 23 '16 at 11:32

1 Answers1

0

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.

Community
  • 1
  • 1
Phiter
  • 14,570
  • 14
  • 50
  • 84
  • Hi Phiter, thanks for this. This seems to output just 's' irrespective of value. – Teege Jun 23 '16 at 12:00
  • Sorry, it still outputs 's' irrespective of the no_slides value. – Teege Jun 23 '16 at 12:14
  • Try echoing your `get_field('no_slides')` and see what is its value before you apply download_text. – Phiter Jun 23 '16 at 12:21
  • This is what I currently use, a number is displayed. – Teege Jun 23 '16 at 12:25
  • The value is bigger than 1? – Phiter Jun 23 '16 at 12:25
  • Yes, I've tested on different values and have the same result 's'. With my original code I get "Download (x Slides)" – Teege Jun 23 '16 at 12:32
  • Ohhh, my bad. It was missing some parenthesis. Take a look at [this example](http://sandbox.onlinephpfunctions.com/code/aa136064741f3d0d4ce3c559b4f381b0ad509623). It works. I'll update my answer. – Phiter Jun 23 '16 at 12:41