Last active
October 16, 2020 23:17
-
-
Save paulsheldrake/9c92fd63057af39ca3a6fc25a2fceeba to your computer and use it in GitHub Desktop.
Output an ACF url field as html. Also allow for extra attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Output ACF url field as HTML. | |
* | |
* Optionally add attributes to the link as an array. | |
* | |
* Example: | |
* | |
* acf_format_link('cp_flex_tab_1', ['class' => 'btn btn-large', 'data-id' => 123]); | |
* | |
* Will render the field like so. | |
* <a href="http://google.com" target="_blank" class="btn btn-large" data-id="123">Link text</a> | |
* | |
* @param string $field_name ACF field machine name. | |
* @param array $attributes A set of attributes to add to the link. | |
* | |
* @return boolean|string | |
*/ | |
function acf_format_link( string $field_name, array $attributes = [] ) { | |
$field = get_field( $field_name ); | |
// Return an empty string if field is empty. | |
if ( ! $field ) { | |
return false; | |
} | |
// Ensure basics. | |
if ( ! isset( $field['title'] ) || empty( $field['title'] ) || ! isset( $field['url'] ) || empty( $field['url'] ) ) { | |
return false; | |
} | |
// Generate attributes string. | |
$attributes_output = ''; | |
if ( ! empty( $attributes ) ) { | |
foreach ( $attributes as $attribute => &$data ) { | |
$data = implode( ' ', (array) $data ); | |
$attributes_output .= $attribute . '="' . esc_attr( $data ) . '" '; | |
} | |
} | |
// Target. | |
$target = ''; | |
if ( ! empty( $field['target'] ) ) { | |
$target = "target='${field["target"]}'"; | |
} | |
$output = "<a href='${field["url"]}' ${target} ${attributes_output}>${field["title"]}</a>"; | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment