I packed everything together. Consider using wp_enqueue_script()
to use the script. With this code, you will save all URLs as an array. See how I use get_post_meta()
to retrieve the saved URLs.
function save_custom_metabox($post_id){
if(!isset($_POST['source_post_metabox_nonce'])) :
return;
endif;
if(!wp_verify_nonce( $_POST['source_post_metabox_nonce'], 'source_post_metabox')) :
return;
endif;
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) :
return;
endif;
if(!current_user_can('edit_post', $post_id))
return;
if ( isset( $_POST['source_post'] ) ) {
foreach( $_POST['source_post'] as $key => $val )
$_POST['source_post'][ $key ] = sanitize_text_field( $val );
update_post_meta( $post_id, '_post_source', $_POST['source_post'] );
}
}
add_action('save_post', 'save_custom_metabox');
function output_source_metabox($post){
wp_nonce_field('source_post_metabox', 'source_post_metabox_nonce');
$post_sources = get_post_meta( $post->ID, '_post_source', true );
if( is_array( $post_sources ) )
foreach( $post_sources as $post_source )
echo '<input type="text" id="source_post" name="source_post[]" value="'.$post_source.'" style="width: 80%;max-width: 720px;"><br />';
else
echo '<input type="text" id="source_post" name="source_post[]" value="" style="width: 80%;max-width: 720px;"><br />';
echo '<button class="add-field">+</button>';
echo '<p>Try to be as specific as possible. <br> E.g. <em>http://tweakers.net/nieuws/101372/ing-belgie-wil-betalingsgedrag-van-klanten-meer-gebruiken-voor-dienstverlening.html</em></p>';
echo '<script>counter = 0;
jQuery(".add-field").click(function( event ) {
event.preventDefault();
counter++;
jQuery("#source_post").after(\'<input type="text" id="source_post_\'+counter+\'" name="source_post[]" value="" style="width: 80%;max-width: 720px;">\');
});</script>';
}
Usage in template files
You can output these URLs in template files like this:
<?php
//We expect $post_sources to be an array
$post_sources = get_post_meta( get_the_ID(), '_post_source', true );
if( ! empty( $post_sources ) && count( $post_sources ) > 0 ):
//Output all sources as a list if sources exist
?>
<ul><?php
foreach( $post_sources as $post_source ):
?>
<li><?php echo $post_source; ?></li>
<?php
endforeach;
?>
</ul>
<?php endif;
if( isset( $post_sources[ 0 ] ) ):
//Output only a single source, in this case the first one
?>
<p><?php echo $post_sources[ 0 ]; ?></p>
<?php
endif;
?>