Skip to content

Instantly share code, notes, and snippets.

@joemaller
Created December 11, 2019 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joemaller/57d13357047cf9d449f6cf9c8f3f1abd to your computer and use it in GitHub Desktop.
Save joemaller/57d13357047cf9d449f6cf9c8f3f1abd to your computer and use it in GitHub Desktop.
/**
* Normalize output from the ACF Link field
*
* Always returns an array, if the field is empty, it returns this empty array:
* ['title' => '', 'url' => '', 'target' => '']
*
* Additionally, if the title is empty, it is populated from the url
*
* Target will be either an empty string or a fully-formed html attribute, like this:
* The array ['target => '_blank']
* Would yield this: "target='_blank'"
*
* This also attempts to extract a post from the url and populates the following:
* $arr[has_post] = boolean
* $arr[post] => the post object or null
*
* TODO: This should probably return an object...
*/
function normalizeAcfLinkField($acfLink)
{
$link = is_array($acfLink) ? $acfLink : ['title' => '', 'url' => '', 'target' => ''];
d(
$link,
parse_url($link['url']),
get_page_by_path(parse_url($link['url'], PHP_URL_PATH), 'OBJECT', ['page', 'news', 'asset', 'team-member'])
);
// d($link, parse_url($link['url'], PHP_URL_PATH), get_page_by_path($link['url']));
if (!empty($link['url'])) {
// d(url_to_postid($link['url']));
$link['post'] = url_to_postid($link['url']) ?: null;
$link['has_post'] = !!$link['post'];
}
if (empty($link['title']) && !empty($link['url'])) {
$link['title'] = $link['url'];
}
if (!empty($link['target'])) {
$link['target'] = "target=\"$link[target]\"";
}
return $link;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment