0

Like when you call the hook 'save_post' to the content div on the page the create/edit post in Admin panel?

Everything is correctly written in the second save function:

$my_dom = new DOMDocument;
$my_html = mb_convert_encoding( $my_html, 'HTML-ENTITIES', 'UTF-8' );
@$my_dom->loadHTML( $my_html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
$my_value = $my_dom->getElementById( 'my_div' )->nodeValue;

...why does the $my_value variable return NULL?

add_action( 'add_meta_boxes', function() {
  add_meta_box(
    'my-div-container',
    'My div',
    function( $post ) {
      wp_nonce_field( basename( __FILE__ ), 'my_div_nonce' );
      $my_html = '<div id="my_div" contenteditable="true">' . get_post_meta( $post->ID, 'my_div', true ) . '</div>';
      echo $my_html;
    },
    'post',
    'normal',
    'high'
  );
});

add_action( 'save_post', function( $post_id ) {
  if ( !isset( $_POST['my_div_nonce'] ) || !wp_verify_nonce( $_POST['my_div_nonce'], basename( __FILE__ ) ) )
    return $post_id;

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

  if ( !current_user_can( 'edit_post', $post_id ) )
    return $post_id;

  $post = get_post( $post_id );
  if ( $post->post_type == 'post' ) {

    $my_dom = new DOMDocument;
    $my_html = mb_convert_encoding( $my_html, 'HTML-ENTITIES', 'UTF-8' );
    @$my_dom->loadHTML( $my_html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
    $my_value = $my_dom->getElementById( 'my_div' )->nodeValue;

    update_post_meta(
      $post_id,
      'my_div',
      $my_value
    );

  }

  return $post_id;
});
  • The $my_html you set in the add_meta_boxes function does not exist in the save_post callback functionm they are in different scopes. Also, div content does not get passed on a form submission. You need to place it in a form input field, or use javascript to pass the value to the server. – czerspalace May 28 '19 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.