Search code examples
phpwordpresspostmeta

display wordpress post meta in editor after save


I am trying to write a small plugin in wordpress, I have a small meta box with text input and a radio button in which user needs to add information, and I want that the imformation that is saved in the post meta box will be displayed after save (in the current state the input text resets to the default plaholder after save).

this is the relevant code:

    add_action( 'add_meta_boxes', 'asset_price' );
function asset_price() {
    add_meta_box( 
        'asset_price',
        __( 'asset price', 'myplugin_textdomain' ),
        'asset_price_box_content',
        'asset',
        'normal',
        'high'
    );
}

function asset_price_box_content( $post ) {
  wp_nonce_field( plugin_basename( __FILE__ ), 'asset_price_box_content_nonce' );
  echo '<label for="asset_price"></label>
        <input type="text" id="asset_price" name="asset_price" placeholder="insert price" />
        <input type="radio" name="currency" value="percent" checked="checked">%
        <input type="radio" name="currency" value="Dollar">$';
    }

add_action( 'save_post', 'asset_price_box_save' );
function asset_price_box_save( $post_id ) {

  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
  return $post_id;

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

  if ( 'page' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) )
    return $post_id; 
  } else {
    if ( !current_user_can( 'edit_post', $post_id ) )
    return $post_id;
  }
  $old = get_post_meta($post_id, "asset_price", true);
$new = $_POST["asset_price"];
if ($new && $new != $old) {
  $product_price = $_POST['asset_price'];
  update_post_meta( $post_id, 'asset_price', $product_price );
}  elseif ('' == $new && $old) {
delete_post_meta($post_id, "asset_price", $old);
}
}

Thanks in advance


Solution

  • You can get the meta box value using get_post_meta() function and display it in the textbox

    function asset_price_box_content( $post ) {
        $price = get_post_meta($post->ID, "asset_price", true);
        wp_nonce_field( plugin_basename( __FILE__ ), 'asset_price_box_content_nonce' );
        echo '<label for="asset_price"></label>
            <input type="text" id="asset_price" name="asset_price" placeholder="insert price" value="'.$price.'" />
            <input type="radio" name="currency" value="percent" checked="checked">%
            <input type="radio" name="currency" value="Dollar">$';
        }