CMB2-Snippet-Library icon indicating copy to clipboard operation
CMB2-Snippet-Library copied to clipboard

[Help needed] Conditionally replacing a field for another

Open pgroot91 opened this issue 5 years ago • 3 comments
trafficstars

Hi Guys,

I wonder if its possible to replace a CMB2 field with another based on another plugins activation that contains a fully customized field.

Plugin 1

  • CORE Plugin
  • Field 1

Plugin 2 (activated)

  • Extension Plugin
  • New Field, should replace the field in the CORE Plugin (Field 1).

The reason is that this field is only for a select group of users. And that is why i want to create that feature in a separate plugin and not including it in the core plugin with a setting.

Any ideas? I haven't seen something like this yet explained yet or must have missed it.

Thanks, Patrick

pgroot91 avatar Jan 24 '20 10:01 pgroot91

As long as you're matching up the meta key, you should be able to save content to the same spot regardless of plugin being used.

For example, the default metabox for custom fields from WP core. Say I create a post and save some fields as _my_meta_field. Then I load up and create a field in CMB2, and specify the field ID to be _my_meta_field. Once I go in to edit that post, the values previously saved would already be filled in to the new CMB2 fields.

I could also edit the same meta field from PHP or some sort of import, and it'd all just take.

The reason I say all this, is that it doesn't necessarily matter how the value is provided, as long as the value saved to the same matching spot. That said though, it depends also on the structure of of the saved data. Simple strings are no issues at all. If one method saves the data as a serialized array, and a different one saves as a string, you'll need to do some type checking and whatnot when it comes time to output to the frontend. Array to string errors aren't always fun :D

tw2113 avatar Jan 24 '20 15:01 tw2113

I just added a snippet that demonstrates deregistering/re-registering a field to replace an existing one: https://github.com/CMB2/CMB2-Snippet-Library/blob/master/filters-and-actions/cmb2_init_%24cmb_id-replace-field.php

However, you can simply replace attributes for an existing field as well: https://github.com/CMB2/CMB2-Snippet-Library/blob/master/filters-and-actions/cmb2_init_before_hookup-add-fields.php#L10-L14

jtsternberg avatar Jan 24 '20 17:01 jtsternberg

Thanks guys for the responses 👍

@jtsternberg the example you provided on first sight looks like exactly what i need!

pgroot91 avatar Jan 24 '20 21:01 pgroot91