Custom Fields
Re-Envisioned
Support MB Custom Table Can't get Meta Box Custom Table to work

This topic contains 6 replies, has 2 voices, and was last updated by  Anh Tran 6 months, 1 week ago.

  • Creator
    Topic
  • #10742
    Resolved
    kesit
    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

Viewing 6 replies - 1 through 6 (of 6 total)
  • Author
    Replies
  • #10753

    Anh 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

    kesit
    Participant

    Ah… I missed that note. Thanks for your response

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

    #10763

    kesit
    Participant

    Sorry, I more question:

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

    #10771

    Anh 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

    kesit
    Participant

    Is it safe for the data?

    Sorry for my late reply…

    #10995

    Anh 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 6 replies - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.