Save a custom field in a custom table when saving a draft

I created a custom metabox with a custom field inside. I attach code.

add_action( 'admin_menu', 'mtb_add_metabox' );

function mtb_add_metabox() {

    add_meta_box(
        'mtb_metabox',
        'Custom name',
        'mtb_metabox_callback', 
        'page',
        'normal',
        'high'
    );

}

function mtb_metabox_callback( $post ) {

    global $wpdb;

    $ct_name = '';

    $query = $wpdb-get_results(
        $wpdb-prepare(
            
            SELECT *
            FROM {$wpdb-prefix}list_name
            WHERE post_id = %d
            ,
            $post-ID
        )
    );

    if($query){

        foreach($query as $value){

            $ct_name = $value-name;

        }

    }

    echo 'table class=form-table
        tbody
            tr
                thlabel for=ct_nameName/label/th
                tdinput type=text id=ct_name name=ct_name value=' . esc_attr($ct_name) . ' class=regular-text/td
            /tr
        /tbody
    /table';
    
}

This custom field I want to save it in a custom table instead of the default wordpress table.

add_action('save_post', 'mtb_save_meta', 10, 3);

function mtb_save_meta($post_id, $post, $update){

   global $wpdb;

   $ct_name = sanitize_text_field($_POST['ct_name']);

   if($update === TRUE){

        $wpdb-query(
            $wpdb-prepare(
                
                UPDATE {$wpdb-prefix}list_name
                SET name = %s,
                WHERE post_id = %d
                ,
                $ct_name,
                $post_id
            )
        );
        
    }else{

        $wpdb-query(
            $wpdb-prepare(
                
                INSERT INTO {$wpdb-prefix}list_name
                (name, post_id)
                VALUES (%s, %d)
                ,
                $ct_name,
                $post_id
            )
        );

    }

}

When I publish the post the custom field is correctly saved in the database but with the automatic saving or clicking on save draft I can not retrieve the value.

The $_POST variable is empty if I click on save draft and the same goes for auto-save.

Can anyone show me how to retrieve the custom fields even when I save the draft?

Thank you very much

Topic save-post custom-field content draft Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.