Article source link for posts

Thats what meta_boxes are for. First you need to register the metabox within the page or post with the function add_meta_box. Then you want to get that value with get_post_meta on the page where you want the “Source”.

This goes into your functions.php file:

/* Define the custom box */
add_action( 'add_meta_boxes', 'wpse_source_link' );

/* Do something with the data entered */
add_action( 'save_post', 'wpse_source_link_save' );

/* Adds a box to the main column on the Post and Page edit screens */
function wpse_source_link() {

    add_meta_box(
        'source_link',
        __( 'Source-link', 'myplugin_textdomain' ), 
        'wpse_source_meta_box',
        'post',
        'side'
    );
}

/* Prints the box content */
function wpse_source_meta_box( $post ) {

  // Use nonce for verification
  wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );

  // The actual fields for data entry
  echo '<input type="text" id="source-link"" name="source_link" value="'. get_post_meta( $post->ID, '_source_link', true ) .'" size="25" />';
}

/* When the post is saved, saves our custom data */
function wpse_source_link_save( $post_id ) {
  // verify if this is an auto save routine. 
  // If it is our form has not been submitted, so we dont want to do anything
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return;

  // verify this came from the our screen and with proper authorization,
  // because save_post can be triggered at other times

  if ( ! wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
      return;


  // Check permissions

  if ( current_user_can( 'edit_post', $post_id ) ) {

      update_post_meta( $post_id, '_source_link', $_POST['source_link'] );

   }
}

This code register the meta_box and stores the value in post_meta as “_source_link”.

It will look like this:

enter image description here

Then you want to get the value in the post, Use get_post_meta:

<?php echo esc_url( get_post_meta( $post->ID, '_source_link', true ) ); ?>

You should read about:
add_meta_boxes,
update_post_meta and
get_post_meta

Leave a Comment