Search code examples
phptextfieldmaxlength

Different MaxLength values


I have an options panel in my WordPress theme with several text fields. For example: Project title, Project description, Twitter username, etc.

case 'text':
    $val = $value['std'];
    $std = get_option($value['id']);
    if ( $std != "") { $val = $std; }
    $output .= '<input class="" maxlength="12" name=""'. $value['id'] .'" id="'. $value['id'] .'" type="'. $value['type'] .'" value="'. $val .'" />';
break;

As the above code shows... I currently have my max length for the text fields as 12, but I would like to have a max length to be different for each of the text fields. How can I do this?

The input IDs for the text fields are mytheme_projectitle1, mytheme_projectitle2, mytheme_projectitle3, mytheme_twitterusername etc. I don't have an input class for any of them, just the ID.


Solution

  • You can access the id for each element with $value['id'] as is apparent from the code. Use that to derive a maximum length, for example this way:

    case 'text':
        // Overrides for the default value of maxlength
        $maxlengths = array(
            'mytheme_projecttitle1' => 10,
            'mytheme_projecttitle2' => 20,
        );
    
        // If there is an override value use it; otherwise use the default of 12
        $maxlen = isset($maxlengths[$value['id']]) ? $maxlengths[$value['id']] : 12;
    
        $val = $value['std'];
        $std = get_option($value['id']);
        if ( $std != "") { $val = $std; }
    
        $output .= '<input class="" maxlength="'.$maxlength.'"..."; // the rest as before