wp_readonly()WP 5.9.0

Outputs readonly='readonly', if the first two parameters of the function match.

The function is needed for convenience when the readonly attribute needs to be output in a form field depending on the value of a php variable.

When comparing values, they are first cast to the same type (string), and then compared:

(string) $one === (string) $two

Thus, a non-exact match will still trigger, for example:

  • int 1 will equal string '1'.
  • true will equal 1 or '1'.
  • false will equal 0 or '0'.
  • etc.

This is one of the helper functions for forms: checked(), disabled(), selected(), wp_readonly().

No Hooks.

Returns

String. String readonly='readonly' or an empty string.

Also, when $echo = true (by default), it outputs the result to the screen.

Usage

<?php wp_readonly( $readonly, $current, $echo ); ?>
$readonly(mixed) (required)
Value to compare. For example true.
$current(mixed)
The second value, will be compared with the first.
Default: true
$echo(true|false)
Whether to output the data to the screen or just return the string.
Default: true

Examples

0

#1 Demo of use

Suppose we have code that defines the $is_readonly variable and if it is true, we need to display the readonly attribute for the form field:

<?php
// some logic ...
$is_readonly = true;
?>

<form ...>
	...
	<input type="text" value="Some string" <?php wp_readonly( $is_readonly ) ?> />
	...
</form>
0

#2 Add the readonly attribute

Suppose you want to add a readonly value to the field if the current user can't edit post 25:

<input type='text' <?php readonly( current_user_can('edit_post', 25 ) ?> name='myname' value='Value' />
0

#3 More examples of how the function works

$is_readonly = true;

wp_readonly( $is_readonly ); // print readonly='readonly'
$is_readonly = false;

wp_readonly( $is_readonly ); // it won't print anything
$readonly = wp_readonly( '1', true, false );

var_dump( $readonly ); // string(20) " readonly='readonly'"

Changelog

Since 5.9.0 Introduced.

wp_readonly() code WP 6.9.1

function wp_readonly( $readonly_value, $current = true, $display = true ) {
	return __checked_selected_helper( $readonly_value, $current, $display, 'readonly' );
}