Skip to content

Default value is ignored with term datasource and only_save_to_taxonomy #711

Open
@dlh01

Description

@dlh01

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:

if ( null === $value && null !== $this->default_value ) {
$value = $this->default_value;
}

However, when only_save_to_taxonomy is used, Fieldmanager_Datasource_Term:: preload_alter_values() will ensure the current value is an array:

public function preload_alter_values( Fieldmanager_Field $field, $values ) {
if ( $this->only_save_to_taxonomy ) {
$taxonomies = $this->get_taxonomies();
$terms = get_terms( array(
'object_ids' => array( $field->data_id ),
'orderby' => 'term_order',
'taxonomy' => array( $taxonomies[0] ),
) );
// If not found, bail out.
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return array();
}
if ( count( $terms ) > 0 ) {
if ( 1 == $field->limit && empty( $field->multiple ) ) {
return $terms[0]->term_id;
} else {
$ret = array();
foreach ( $terms as $term ) {
$ret[] = $term->term_id;
}
return $ret;
}
}
}
return $values;
}
.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions