MB Custom Table and wp_insert_post

Support MB Custom Table MB Custom Table and wp_insert_postResolved

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #14689
    wgstjfwgstjf
    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

    #14693
    Anh TranAnh 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
    wgstjfwgstjf
    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 TranAnh 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 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.