CMB2 / CMB2-Snippet-Library

CMB2 Code Snippet Library
360 stars 146 forks source link

[Help needed] Conditionally replacing a field for another #102

Open pgroot91 opened 4 years ago

pgroot91 commented 4 years ago

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

Plugin 2 (activated)

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

tw2113 commented 4 years ago

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

jtsternberg commented 4 years ago

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

pgroot91 commented 4 years ago

Thanks guys for the responses 👍

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