Can't get Meta Box Custom Table to work

Support MB Custom Table Can't get Meta Box Custom Table to workResolved

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #10742
    kesitkesit
    Participant

    Hi,
    would you mind to suggest where do I go wrong?

    I've placed below code in functions.php

    add_action( 'init', 'prefix_create_table' );
    
    function prefix_create_table() {
        global $wpdb;
        
        if ( ! class_exists( 'MB_Custom_Table_API' ) ) {
            return;
        }
        MB_Custom_Table_API::create( $wpdb->prefix.'data_khusus', array(
            'test_column' => 'TEXT NOT NULL'  ,
            'test_column2' => 'TEXT NOT NULL'  ,    
        ), array( 'test_column' ) );
    }

    But the above code is not working. No table is created and, of course, no data saved.
    Is there any idea to fix my code here?

    Thanks

    #10753
    Anh TranAnh Tran
    Keymaster

    Hi,

    In the docs:

    BLOB and TEXT columns also can be indexed, but a fixed length must be given. Make sure you set the length when you want to index a text column.

    In your code, you make the test_column indexed, but it doesn't have a fixed length. So the code won't run. Change it to the following code will work:

    MB_Custom_Table_API::create( $wpdb->prefix.'data_khusus', array(
        'test_column' => 'VARCHAR(20) NOT NULL',
        'test_column2' => 'TEXT NOT NULL',    
    ), array( 'test_column' ) );
    #10762
    kesitkesit
    Participant

    Ah... I missed that note. Thanks for your response

    And thank you for these great plugins! keep up the good work!

    #10763
    kesitkesit
    Participant

    Sorry, I more question:

    Is it possible to move existing meta value from default post meta table into custom table?

    #10771
    Anh TranAnh Tran
    Keymaster

    Hi kesit,

    You need to write custom code to move the data from custom fields to custom table. Here is a sample code:

    $post_id = 1;
    $fields = ['field_1', 'field_2'];
    $table = 'your_custom_table';
    
    $row = ['ID' => $post_id];
    foreach ( $fields as $field ) {
        $row[$field] = get_post_meta( $post_id, $field, true );
    }
    global $wpdb;
    $wpdb->insert( $table, $row );
    #10992
    kesitkesit
    Participant

    Is it safe for the data?

    Sorry for my late reply...

    #10995
    Anh TranAnh Tran
    Keymaster

    Yes, it's safe. In the code above, there's no code to remove the data. So it always there.

    You should always backup the database before doing this.

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.