Using WordPress ‘readonly()’ PHP function

The readonly() WordPress PHP function outputs the HTML readonly attribute by comparing the first two arguments. If they are identical, the attribute is marked as readonly. This function is deprecated and cannot be used on PHP >= 8.1. Instead, use wp_readonly().

Usage

readonly($readonly_value, $current = true, $display = true);

Parameters

  • $readonly_value (mixed) – One of the values to compare.
  • $current (mixed) – Optional. The other value to compare if not just true. Default is true.
  • $display (bool) – Optional. Whether to echo or just return the string. Default is true.

More information

See WordPress Developer Resources: readonly()

This function is deprecated and cannot be used on PHP >= 8.1. Use wp_readonly() instead.

Examples

Basic usage of readonly() function

This example shows how to use the readonly() function to mark an input field as readonly:

// Check if the user role is "subscriber"
$is_subscriber = (get_current_user_role() == "subscriber");

// Display a readonly input field if the user role is "subscriber"
echo '<input type="text" name="example" value="Sample Text" ';
readonly($is_subscriber);
echo ' />';

Using readonly() with custom comparison values

This example demonstrates using the readonly() function with custom comparison values:

// Sample variables
$value1 = 5;
$value2 = 5;

// Display a readonly input field if the two values are equal
echo '<input type="number" name="example" value="5" ';
readonly($value1, $value2);
echo ' />';

Returning readonly attribute without echoing

This example shows how to use the readonly() function to return the readonly attribute without echoing it:

// Check if the user role is "subscriber"
$is_subscriber = (get_current_user_role() == "subscriber");

// Get the readonly attribute
$readonly_attribute = readonly($is_subscriber, true, false);

// Display an input field with the returned attribute
echo '<input type="text" name="example" value="Sample Text" ' . $readonly_attribute . ' />';

Marking a textarea as readonly

This example demonstrates marking a textarea as readonly using the readonly() function:

// Check if the user role is "subscriber"
$is_subscriber = (get_current_user_role() == "subscriber");

// Display a readonly textarea if the user role is "subscriber"
echo '<textarea name="example" ';
readonly($is_subscriber);
echo '>Sample Text</textarea>';

Using readonly() with an array

This example shows how to use the readonly() function with an array:

// Sample array and value
$array = array('apple', 'banana', 'orange');
$value = 'banana';

// Display a readonly input field if the value is in the array
echo '<input type="text" name="example" value="banana" ';
readonly(in_array($value, $array));
echo ' />';