Custom Fields
Re-Envisioned
Support MB Custom Table MB Custom Table and wp_insert_post

This topic contains 3 replies, has 2 voices, and was last updated by  Anh Tran 2 months, 3 weeks ago.

  • Creator
    Topic
  • #14689
    Resolved
    wgstjf
    Participant

    Hi,

    We’re working with Custom Table for a client site where we know that there will be a lot of data. We have successfully migrated from the normal post_meta method by installing the plugin and creating the table. In the admin area all is working well.

    Our issue is that posts are created by frontend users and the current code relies on the wp_insert_post to create the post and add the meta data. Using this method the meta data is being stored the WP’s post_meta table rather than the new custom table.

    Can you let me know how we can get WP to store the meta data in the new custom table please?

    Cheers,

    Will

Viewing 3 replies - 1 through 3 (of 3 total)
  • Author
    Replies
  • #14693

    Anh Tran
    Keymaster

    Hi Will,

    When you insert posts, please don’t use add_post_meta to add custom fields. Instead, use $wpdb to insert data to the custom table, like this:

    global $wpdb;
    $post_id = wp_insert_post( $post_data );
    $custom_fields = [
        'ID' => $post_id,
        'field_1' => $value_1,
        'field_2' => $value_2,
    ];
    $wpdb->insert( 'custom_table', $custom_fields );
    #14702

    wgstjf
    Participant

    That’s great, thanks.

    Are there any knock-on effects when doing WP_Query meta_querys? Does it work as normal?

    Cheers,

    Will

    #14756

    Anh Tran
    Keymaster

    Hi Will,

    For WP_Query, the plugin doesn’t integrate with it. You need to perform an extra query to get the posts you want, then use the returned ID to create your own WP_Query.

    global $wpdb;
    $ids = $wpdb->get_col( "SELECT ID FROM your_table WHERE field1='value1' OR field2='value2'" );
    
    $query = new WP_Query( [
        'post_type' => 'post',
        'post__in'  => $id,
    ] );
Viewing 3 replies - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.