alleyinteractive / wordpress-fieldmanager

Custom field types for WordPress
Other
533 stars 101 forks source link

Default value is ignored with term datasource and `only_save_to_taxonomy` #711

Open dlh01 opened 6 years ago

dlh01 commented 6 years ago

When a field uses a Fieldmanager_Datasource_Term with 'only_save_to_taxonomy' => true, the field's default_value is ignored.

For example, in this field intended to replace the default category selection meta box, the first option in the <select> element will always be selected when creating a post:

<?php
new \Fieldmanager_Select( [
    'name' => 'category',
    'datasource' => new \Fieldmanager_Datasource_Term ( [
        'taxonomy' => 'category',
        'only_save_to_taxonomy' => true,
    ] ),
    'default_value' => get_option( 'default_category' ),
] );

I think this happens because of logic in Fieldmanager_Datasource_Term.

A field's default_value is used only when the current value is null: https://github.com/alleyinteractive/wordpress-fieldmanager/blob/10080e822affeea0a71ec717746e153f9a4406ec/php/class-fieldmanager-field.php#L700-L702

However, when only_save_to_taxonomy is used, Fieldmanager_Datasource_Term:: preload_alter_values() will ensure the current value is an array: https://github.com/alleyinteractive/wordpress-fieldmanager/blob/10080e822affeea0a71ec717746e153f9a4406ec/php/datasource/class-fieldmanager-datasource-term.php#L141-L168.

mboynes commented 1 year ago

What’s tricky about this is: we have no way to differentiate between the field being empty (deliberately, because no term was selected and the post was saved) and the field being uninitialized. When we save to post meta, we can determine that based on if the meta exists (even if the value is empty) or not. But if we’re dependent on the term relationship, we don't have that luxury. Whether this field has ever been saved or not will result in the same term query and, if saved with no term(s) selected, the same results.