<?php
function wp_create_links( $link_data ) {
$links = array();
if ( isset( $link_data ) && is_array( $link_data ) ) {
foreach ( $link_data as $key => $link ) {
$attributes = array();
if ( isset( $link['attributes'] ) && is_array( $link['attributes'] ) ) {
$attributes = $link['attributes'];
}
// URL check.
if ( empty( $link['url'] ) || ! is_string( $link['url'] ) || '' === trim( $link['url'] ) ) {
continue;
}
// Label check.
if ( empty( $link['label'] ) || ! is_string( $link['label'] ) || '' === trim( $link['label'] ) ) {
continue;
}
// Current check.
if ( ! empty( $link['is_current'] ) && true === $link['is_current'] ) {
$attributes['aria-current'] = 'page';
if ( empty( $attributes['class'] ) ) {
$attributes['class'] = 'current';
} else {
$attributes['class'] .= ' current';
}
}
// Collapse attributes to attribute="value" or boolean attributes.
$attributes = array_map(
function( $attribute, $value ) {
// Mark invalid/empty attributes for removal.
if ( empty( $attribute ) || ! is_string( $attribute ) ) {
return false;
}
// Convert `int` and `float` values to `string`.
if ( is_int( $value ) || is_float( $value ) ) {
$value = (string) $value;
}
// Mark non-string values for removal.
if ( ! is_string( $value ) ) {
return false;
}
// On an empty `value`, assume this is a boolean attribute.
if ( empty( $value ) ) {
return $attribute;
}
return sprintf(
'%s="%s"',
$attribute,
$value
);
},
array_keys( $attributes ),
array_values( $attributes )
);
// Clean up attributes.
$attributes = array_filter( $attributes );
// Generate link.
$links[ $key ] = sprintf(
'<a href="%s"%s>%s</a>',
$link['url'],
! empty( $attributes ) ? ' ' . implode( ' ', $attributes ) : '',
$link['label']
);
}
}
return $links;
}
$links = wp_create_links(
array(
'my_link' => array(
'url' => 'https://example.org',
'label' => 'My Example Link',
'is_current' => true,
'attributes' => array(
'class' => 'hello',
'rel' => 'nofollow noreferrer',
'disabled' => '',
),
),
'my_other_link' => array(
'url' => 'https://example.com',
'label' => 'My Other Example Link',
'is_current' => true,
'attributes' => array(
'class' => 'hello',
'rel' => 'nofollow noreferrer',
'disabled' => '',
),
),
)
);
var_dump( $links['my_link'] );
preferences:
57.93 ms | 411 KiB | 5 Q