• Resolved J M

    (@hiphopinenglish)


    Hi there.
    Been using CMB for a while and recently changed to CMB2. All working wonderfully, so thanks for a great project.

    I was wondering how I might go about sanitizing my data outside a metabox context? Right now, I’m importing post content and meta data via .csv files which save the data to the database. I’m using some fairly rudimentary sanitization checks right now, and since I’m using CMB2 I’d like to hook in to its sanitization capabilities.

    I can pass a metabox id, meta key and value but I’ve scoured the code for a function to hook into and not found one. Any help would be greatly appreciated. Thanks.

    https://www.ads-software.com/plugins/cmb2/

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Author Justin Sternberg

    (@jtsternberg)

    The easiest way would be to use the save_fields() CMB2 method. A helper function would look something like this:

    /**
     * Save fields data from an array of data (Likely $_POST data.)
     *
     * @param  mixed  $meta_box_id  Metabox ID (or metabox config array)
     * @param  int    $post_id      ID of post to save the data against
     * @param  array  $data_to_save Array of key => value data for saving. Likely $_POST data.
     */
    function cmb2_save_metabox_post_fields( $meta_box_id, $post_id, array $data_to_save ) {
    	$cmb = cmb2_get_metabox( $meta_box_id, $post_id );
    	$cmb->save_fields( $post_id, $cmb->object_type(), $data_to_save );
    }

    You shouldn’t use this till at least the cmb2_after_init hook though. And you wouldn’t pass it one value, you’d pass it an array of ‘key’ => ‘value’ pairs where ‘key’ is the field id, and ‘value’ obviously being the value you want saved to that post meta field. save_fields() will ignore anything in the $data_to_save array that is not one of the metabox field ids.

    Plugin Author Justin Sternberg

    (@jtsternberg)

    Thread Starter J M

    (@hiphopinenglish)

    That’s awesome. Thanks. I’ve implemented it and it works though I’ll do some more testing to make sure I’m passing it everything I need to pass it. I do have another question, though: How can I go about returning a message to the user if save_fields ignores a particular value for a key if it doesn’t pass the sanitization check?

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Sanitizing data outside metabox context’ is closed to new replies.