'image', 'id' => $id, 'url' => (string) wp_get_attachment_image_url( $id, 'large' ), 'x' => $percent( $cover['x'] ?? null, 50 ), 'y' => $percent( $cover['y'] ?? null, 50 ), 'overlay' => min( 80, $percent( $cover['overlay'] ?? null, 35 ) ), ); } elseif ( 'gradient' === $cover['type'] ) { $from = sanitize_hex_color( $cover['from'] ?? '' ); $to = sanitize_hex_color( $cover['to'] ?? '' ); if ( ! $from || ! $to ) { return ''; } $clean = array( 'type' => 'gradient', 'from' => $from, 'to' => $to, 'angle' => is_numeric( $cover['angle'] ?? null ) ? ( (int) $cover['angle'] % 360 + 360 ) % 360 : 135, ); } else { return ''; } return (string) wp_json_encode( $clean, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); } /** * Parsed cover of a term. * * @param int $term_id Term. * @return array|null */ public static function get( $term_id ) { $cover = json_decode( (string) get_term_meta( (int) $term_id, self::META, true ), true ); return is_array( $cover ) && ! empty( $cover['type'] ) ? $cover : null; } /** * Inline style for an element showing a term's cover, or '' without one. * * Sets the background and the --kdocs-cover-overlay variable; templates add the * `kdocs-has-cover` class when this is not empty. * * @param int $term_id Term. * @param string $size Image size. * @return string Escaped style attribute value. */ public static function style( $term_id, $size = 'large' ) { $cover = self::get( $term_id ); if ( ! $cover ) { return ''; } if ( 'gradient' === $cover['type'] ) { return esc_attr( sprintf( 'background-image:linear-gradient(%ddeg,%s,%s)', (int) $cover['angle'], $cover['from'], $cover['to'] ) ); } $url = wp_get_attachment_image_url( (int) $cover['id'], $size ); if ( ! $url ) { return ''; } return esc_attr( sprintf( 'background-image:url("%s");background-position:%d%% %d%%;--kdocs-cover-overlay:%s', esc_url_raw( $url ), (int) $cover['x'], (int) $cover['y'], number_format( (int) $cover['overlay'] / 100, 2, '.', '' ) ) ); } }