post_type, $taxonomy ) ) { return null; } $terms = get_the_terms( $post, $taxonomy ); if ( ! is_array( $terms ) || array() === $terms ) { return null; } $primary = self::post( $post->ID, 'primary_terms' ); $chosen = is_array( $primary ) ? (int) ( $primary[ $taxonomy ] ?? 0 ) : 0; if ( $chosen ) { foreach ( $terms as $term ) { if ( (int) $term->term_id === $chosen ) { return $term; } } } /** * Filters the fallback primary term when none was chosen. * * @param WP_Term $term First assigned term. * @param WP_Post $post Post. * @param string $taxonomy Taxonomy. * @param WP_Term[] $terms All assigned terms. */ $term = apply_filters( 'wpiseo_primary_term_fallback', $terms[0], $post, $taxonomy, $terms ); return $term instanceof WP_Term ? $term : $terms[0]; } /** * Reads and normalises a field. * * @param string $object_type Object type. * @param int $object_id Object ID. * @param string $key Field key without prefix. * @return mixed */ private static function read( string $object_type, int $object_id, string $key ) { $fields = Fields::for_type( $object_type ); if ( ! isset( $fields[ $key ] ) ) { return null; } $spec = $fields[ $key ]; $value = $object_id ? get_metadata( $object_type, $object_id, Fields::PREFIX . $key, true ) : ''; if ( '' === $value || null === $value || false === $value ) { return Fields::default_value( $spec ); } switch ( $spec['type'] ) { case 'boolean': return (bool) $value; case 'integer': return (int) $value; case 'array': case 'object': return is_array( $value ) ? $value : Fields::default_value( $spec ); default: return is_scalar( $value ) ? (string) $value : ''; } } }