Description
The Link field allows a link to be selected or defined (url, title, target) by using the native WordPress link popup.
Screenshots
Changelog
- Added in version 5.6.0.
Settings
- Return value
Specifies the format of the returned data. Choose from Link Array (array of data) or Link URL (string).
Template usage
The Link field will return either an array or string depending on the return value setting. Below are some examples of how you can use this data.
Basic display (array)
This example demonstrates how to display the selected link when using the Link Array
return type.
<?php
$link = get_field('link');
if( $link ):
$link_url = $link['url'];
$link_title = $link['title'];
$link_target = $link['target'] ? $link['target'] : '_self';
?>
<a class="button" href="<?php echo esc_url( $link_url ); ?>" target="<?php echo esc_attr( $link_target ); ?>"><?php echo esc_html( $link_title ); ?></a>
<?php endif; ?>
Basic display (string)
This example demonstrates how to display the selected link when using the Link URL
return type.
<?php
$link = get_field('link');
if( $link ): ?>
<a class="button" href="<?php echo esc_url( $link ); ?>">Continue Reading</a>
<?php endif; ?>
Require input in link field
Depending on how you are using the link field’s data, you may want to require the link text field be filled out, especially if using it for accessibility purposes.
You can add a custom validation function to require the link text field be completed using the acf/validate_value
filter like this:
function my_custom_validation_callback_function( $valid, $value, $field, $input_name ) {
// If the field type being validated is a link field, the return format is "array", and the title is blank.
if ( 'link' === $field['type'] && 'array' === $field['return_format'] && empty( $value['title'] ) ) {
// Show an error message.
return __( 'Please ensure you have entered a value for the link text.' );
}
// Otherwise, don't change anything.
return $valid;
}
add_filter( 'acf/validate_value', 'my_custom_validation_callback_function', 10, 4 );
Supercharge Your Website With Premium Features Using ACF PRO
Speed up your workflow and unlock features to better develop websites using ACF Blocks and Options Pages, with the Flexible Content, Repeater, Clone, Gallery Fields & More.
Related
- Content: File
- Field Types: User
- Content: Image
- Choice: Radio Button
- Choice: Button Group