You can add the extra (link/URL label) field like so:
In the wpse_source_meta_box()
function, add the (HTML of the) extra field:
echo '<input type="text" id="source-link-label"" name="source_link_label" value="'.
get_post_meta( $post->ID, '_source_link_label', true ) .'" size="25" />';
so as you can see, the field name is _source_link_label
as used in the get_post_meta()
call when retrieving the field value.
However, since there are now two fields, you may want to add a placeholder
to the input
fields:
echo '<input type="text" id="source-link"" name="source_link" value="'.
get_post_meta( $post->ID, '_source_link', true ) .'" size="25" placeholder="URL" />';
echo '<input type="text" id="source-link-label"" name="source_link_label" value="'.
get_post_meta( $post->ID, '_source_link_label', true ) .'" size="25" placeholder="Label" />';
Or add a <label>
before the fields:
echo '<label for="source-link">URL:</label> ';
echo '<input type="text" id="source-link"" name="source_link" value="'.
get_post_meta( $post->ID, '_source_link', true ) .'" size="25" />';
echo '<label for="source-link-label">Label:</label> ';
echo '<input type="text" id="source-link-label"" name="source_link_label" value="'.
get_post_meta( $post->ID, '_source_link_label', true ) .'" size="25" />';
In the wpse_source_link_save()
function, save/update the field value like so:
update_post_meta( $post_id, '_source_link_label', $_POST['source_link_label'] );
And then use the field value (or the link label) along with the link URL, like so:
<?php
// Show if the source link was specified.
if ( $url = get_post_meta( $post->ID, '_source_link', true ) ) :
$label = get_post_meta( $post->ID, '_source_link_label', true );
$label = $label ? $label : $url;
?>
<div class="source-link">
Source: <a href="<?php echo esc_url( $url ); ?>"><?php // wrapped (for clarity)
echo esc_html( $label ); ?></a>
</div>
<?php endif; // end $url ?>
(Part of the code was taken from here.)
So the full code, without the step #3's part, would look like this. :)
That should work, but I suggest you to use sanitize_text_field()
when updating the fields:
update_post_meta( $post_id, '_source_link', sanitize_text_field( $_POST['source_link'] ) );
update_post_meta( $post_id, '_source_link_label', sanitize_text_field( $_POST['source_link_label'] ) );
See this article for more details on that.