01
Início rápido
Use os exemplos em um template ou tema filho. $imageId, $videoId e $attachmentId são IDs existentes de anexos. As funções retornam dados ou HTML, sem converter arquivos durante a requisição.
<?php
$imageId = (int) get_post_thumbnail_id();
if ($imageId > 0) {
echo function_exists('akita_media_picture')
? akita_media_picture($imageId, ['profile' => 'hero'])
: wp_get_attachment_image($imageId, 'large');
}
02
Imagens responsivas
picture() retorna fontes AVIF/WebP e o img do WordPress como alternativa. get() contém attachment_id, source_attachment_id, optimized, fallback, sources, status, error e profile. sources usa o formato como chave.
<?php
echo akita_media_picture($imageId, [
'size' => 'large',
'formats' => ['avif', 'webp'],
'sizes' => '(max-width: 768px) 100vw, 1200px',
'class' => 'hero__image',
'picture_class' => 'hero__picture',
'alt' => get_post_meta($imageId, '_wp_attachment_image_alt', true),
'loading' => 'eager',
'fetchpriority' => 'high',
'decoding' => 'async',
'attributes' => ['data-media' => 'hero'],
]);
$image = akita_media_get($imageId, ['profile' => 'card']);
$fallbackUrl = $image['fallback']['url'] ?? '';
$webpSrcset = $image['sources']['webp']['srcset'] ?? '';
Opções disponíveis
| Parâmetro | Comportamento e retorno |
|---|---|
profile | Nome do perfil. Opções explícitas têm prioridade. |
size | Tamanho WordPress ou [largura, altura]. Padrão: full. |
formats | Ordem dos formatos, padrão ['avif', 'webp']. |
sizes | Largura responsiva no layout; caso contrário, perfil ou WordPress. |
class / picture_class | Classes de img/picture. picture exige fontes modernas. |
alt | Texto alternativo; por padrão, metadados do anexo. |
loading / fetchpriority / decoding | lazy|eager; high|low|auto; async|sync|auto. Perfis podem definir padrões. |
attributes | Atributos permitidos: id, title, data-* e aria-*. Sem eventos ou substituição direta de src. |
03
Perfis padrão e personalizados
Um perfil reúne larguras, corte e atributos de entrega. Registre em after_setup_theme com prioridade 10, antes dos tamanhos registrados pelo plugin na prioridade 20.
| Perfil | Larguras, px | Comportamento e retorno |
|---|---|---|
hero | 768, 1280, 1920 | Corte 16:9, eager, prioridade high, sizes=100vw. |
card | 320, 640, 960 | Corte 4:3, lazy, prioridade auto, 100vw / 33vw. |
gallery | 480, 960, 1440 | Proporções originais, lazy, prioridade auto, 100vw / 50vw. |
<?php
add_action('after_setup_theme', function (): void {
if (! function_exists('akita_media_register_profile')) {
return;
}
akita_media_register_profile('case-study', [
'widths' => [600, 1200, 1800],
'aspect_ratio' => '3:2',
'crop' => ['center', 'top'],
'formats' => ['avif', 'webp'],
'sizes' => '(max-width: 768px) 100vw, 1200px',
'loading' => 'lazy',
'fetchpriority' => 'auto',
'decoding' => 'async',
'class' => 'case-study__image',
'picture_class' => 'case-study__picture',
]);
}, 10);
<?php
$profiles = akita_media_profiles();
echo akita_media_picture($imageId, ['profile' => 'case-study']);
- widths: inteiros únicos de 64 a 8192. aspect_ratio: W:H, [W, H] ou null.
- crop: true, false ou [left|center|right, top|center|bottom]. Sem proporção, a original é preservada.
- Argumentos explícitos substituem o perfil. Um perfil desconhecido informa unknown_profile e usa a imagem normal.
Opções disponíveis
| Parâmetro | Comportamento e retorno |
|---|---|
widths | Lista obrigatória de larguras de 64 a 8192 px. |
aspect_ratio / crop | W:H ou [W, H]; null preserva proporções. Admite posições de corte. |
formats / sizes | Formatos e padrões de entrega responsiva. |
class / picture_class / loading / fetchpriority / decoding | Atributos padrão que os argumentos da chamada podem substituir. |
04
ACF: imagens, galerias e arquivos
O resolver aceita ID, string numérica, array com ID/id/attachment_id/url, WP_Post, URL local ou uma lista. Mantém a ordem e remove IDs duplicados.
<?php
if (function_exists('get_field') && function_exists('akita_media_resolve_acf')) {
$image = akita_media_resolve_acf(get_field('hero_image'));
foreach ($image['attachment_ids'] as $imageId) {
echo akita_media_picture($imageId, ['profile' => 'hero']);
}
$gallery = akita_media_resolve_acf(get_field('gallery'));
foreach ($gallery['attachment_ids'] as $imageId) {
echo akita_media_picture($imageId, ['profile' => 'gallery']);
}
$video = akita_media_resolve_acf(get_field('video_file'));
foreach ($video['items'] as $item) {
if ($item['media_type'] === 'video') {
echo akita_media_video($item['attachment_id']);
}
}
}
<?php
$files = akita_media_resolve_acf(get_field('download_file'));
foreach ($files['items'] as $file) {
if ($file['media_type'] === 'file' && $file['url'] !== '') {
printf('<a href="%s">%s</a>', esc_url($file['url']), esc_html($file['title']));
}
}
- Retorno: multiple, attachment_ids, items e error. Sem mídia: listas vazias e attachment_not_found.
- Imagens oferecem dados responsivos; vídeos, url/webm_url/sources/poster_url. Outros arquivos mantêm original e optimized=false.
- Traduções WPML do mesmo arquivo físico compartilham derivados, preservando title e alt traduzidos.
05
Fontes de vídeo e pôsteres
video() usa WebM verificado antes do MP4 ou original disponível. video_sources() retorna {url, type} para HTML próprio. A posição do pôster é definida nas configurações.
<?php
echo akita_media_video($videoId, [
'class' => 'project-video',
'controls' => true,
'playsinline' => true,
'preload' => 'metadata',
'width' => 1280,
'height' => 720,
]);
<video controls playsinline preload="metadata"
poster="<?= esc_url(akita_media_poster_url($videoId, 'large')); ?>">
<?php foreach (akita_media_video_sources($videoId) as $source) { ?>
<source src="<?= esc_url($source['url']); ?>"
type="<?= esc_attr($source['type']); ?>">
<?php } ?>
</video>
<?php
$deliveryId = akita_media_video_id($videoId);
$deliveryUrl = akita_media_video_url($videoId);
$webmId = akita_media_video_webm_id($videoId);
$webmUrl = akita_media_video_webm_url($videoId);
$posterId = akita_media_poster_id($videoId);
$posterUrl = akita_media_poster_url($videoId, 'large');
- video_id/url retornam MP4 gerado ou original, sem iniciar conversão.
- Sem WebM ou pôster: ID=0 e URL vazia. poster='' omite o pôster; uma URL o substitui.
- Use esc_url() e esc_attr() no HTML próprio.
Opções disponíveis
| Parâmetro | Comportamento e retorno |
|---|---|
poster | Pôster gerado por padrão; URL substitui; string vazia omite. |
preload | none, metadata (padrão) ou auto. |
autoplay / controls / loop / muted / playsinline | Booleanos. controls/playsinline são true por padrão, os demais false. autoplay geralmente exige muted. |
id / class / aria-label | Atributos de identificação e acessibilidade aceitos. |
width / height | Dimensões inteiras positivas, sem iniciar conversão. |
06
Fundos CSS
background_style() retorna background-image original, seguido de image-set() quando existem fontes verificadas. Escape todo o atributo style com esc_attr().
<section class="page-hero"
style="<?= esc_attr(akita_media_background_style($imageId, ['profile' => 'hero'])); ?>">
...
</section>
<?php
$originalUrl = akita_media_background_url($imageId, ['size' => 'large']);
$webpUrl = akita_media_background_url($imageId, [
'size' => 'large',
'format' => 'webp',
]);
07
Entrega automática do WordPress
Ative nas configurações ou pelo helper para wp_get_attachment_image() e blocos core/image. Preserva o img e não envolve novamente um picture existente.
<?php
add_action('after_setup_theme', function (): void {
if (! function_exists('akita_media_enable_content_integration')) {
return;
}
akita_media_enable_content_integration([
'attachment_images' => true,
'core_image_blocks' => true,
'formats' => ['avif', 'webp'],
'picture_class' => 'site-picture',
'include' => static fn (int $id, string $context, array $args): bool => ! is_feed(),
]);
}, 30);
<?php
add_action('wp', function (): void {
if (is_page_template('templates/raw-media.php')
&& function_exists('akita_media_disable_content_integration')) {
akita_media_disable_content_integration();
}
});
- include recebe ID, contexto attachment_image/core_image_block e argumentos.
- disable_content_integration() remove os filtros da requisição atual, sem alterar configurações salvas.
Opções disponíveis
| Parâmetro | Comportamento e retorno |
|---|---|
attachment_images / core_image_blocks | Controles separados, ambos true por padrão. |
formats / profile / picture_class | Ordem dos formatos, perfil opcional e uma classe picture. |
include | Callback opcional (int $id, string $context, array $args): bool. |
08
Fonte e prontidão
source_id() encontra a fonte física com WPML. status() lê seu estado salvo. is_ready() é true apenas para ready.
<?php
$sourceId = akita_media_source_id($attachmentId);
$status = akita_media_status($attachmentId);
$ready = akita_media_is_ready($attachmentId);
echo akita_media_picture($imageId, ['profile' => 'card']);
09
Filtros de entrega
resolved_image recebe dados, ID e argumentos e retorna array. picture_html recebe HTML, dados, ID e argumentos e retorna string. auto_delivery_args recebe argumentos, ID, contexto e seus dados.
<?php
add_filter('akita_media_auto_delivery_args', function (
array $args,
int $attachmentId,
string $context,
array $contextData
): ?array {
if (is_feed()) {
return null;
}
$args['formats'] = ['webp'];
return $args;
}, 10, 4);
<?php
add_filter('akita_media_resolved_image', function (
array $image,
int $attachmentId,
array $args
): array {
$image['theme_context'] = $args['profile'] ?? null;
return $image;
}, 10, 3);
add_filter('akita_media_picture_html', function (
string $html,
array $image,
int $attachmentId,
array $args
): string {
return str_replace('<picture', '<picture data-theme="project"', $html);
}, 10, 4);
10
Todas as 20 funções públicas
Cada entrada mostra assinatura, retorno e chamada mínima. Consulte as seções anteriores para ciclo do WordPress, verificações do plugin e escape de HTML.
akita_media_get(int $attachmentId, array $args = []): array- Dados normalizados; fallback pode ser null e sources vazio.
$image = akita_media_get($imageId, ['size' => 'large']);akita_media_picture(int $attachmentId, array $args = []): string- HTML picture ou img WordPress; string vazia sem imagem válida.
echo akita_media_picture($imageId, ['profile' => 'hero']);akita_media_register_profile(string $name, array $config): bool- Registra o perfil e retorna true. Dados inválidos: InvalidArgumentException.
akita_media_register_profile('square', ['widths' => [320, 640], 'aspect_ratio' => '1:1']);akita_media_profiles(): array- Todos os perfis indexados pelo nome.
$hero = akita_media_profiles()['hero'] ?? null;akita_media_resolve_acf(mixed $value, array $args = []): array- Coleção com multiple, attachment_ids, items e error.
$gallery = akita_media_resolve_acf(get_field('gallery'), ['profile' => 'gallery']);akita_media_enable_content_integration(array $config = []): bool- Ativa filtros de imagem/bloco nesta requisição e retorna true.
akita_media_enable_content_integration(['picture_class' => 'site-picture']);akita_media_disable_content_integration(): void- Remove os filtros automáticos desta requisição.
akita_media_disable_content_integration();akita_media_background_style(int $attachmentId, array $args = []): string- CSS com original e image-set() opcional; vazio sem alternativa.
$css = akita_media_background_style($imageId, ['profile' => 'hero']);akita_media_background_url(int $attachmentId, array $args = []): string- URL do formato ou original. Formato padrão: original.
$url = akita_media_background_url($imageId, ['format' => 'webp']);akita_media_source_id(int $attachmentId): int- ID da fonte física com correspondência WPML.
$sourceId = akita_media_source_id($attachmentId);akita_media_video_id(int $attachmentId): int- ID do MP4 gerado ou do anexo original.
$deliveryId = akita_media_video_id($videoId);akita_media_video_url(int $attachmentId): string- URL de MP4 ou original, ou string vazia.
$url = akita_media_video_url($videoId);akita_media_video_webm_id(int $attachmentId): int- ID do WebM gerado ou 0.
$webmId = akita_media_video_webm_id($videoId);akita_media_video_webm_url(int $attachmentId): string- URL de WebM ou string vazia.
$webmUrl = akita_media_video_webm_url($videoId);akita_media_video_sources(int $attachmentId): array- Lista {url, type}, WebM antes da alternativa; pode estar vazia.
$sources = akita_media_video_sources($videoId);akita_media_video(int $attachmentId, array $args = []): string- HTML video/source com pôster opcional, ou string vazia.
echo akita_media_video($videoId, ['controls' => true]);akita_media_poster_id(int $attachmentId): int- ID do pôster ou 0.
$posterId = akita_media_poster_id($videoId);akita_media_poster_url(int $attachmentId, string $size = 'full'): string- URL do pôster em um tamanho WordPress, ou string vazia.
$posterUrl = akita_media_poster_url($videoId, 'large');akita_media_status(int $attachmentId): string- Estado salvo da imagem/vídeo fonte, ou string vazia.
$status = akita_media_status($attachmentId);akita_media_is_ready(int $attachmentId): bool- true apenas quando o estado da fonte é ready.
$ready = akita_media_is_ready($attachmentId);
11
Verificação e solução de problemas
Verifique tanto a geração quanto o uso dos arquivos em uma página real.
- Confira codificadores e agendamentos em Saúde do site. O WP-Cron padrão não exige SSH.
- Regenere tamanhos ausentes, analise a biblioteca e aguarde a fila.
- Inspecione picture/source e as requisições de rede. A alternativa é normal quando um formato está ausente.
- Após mudar políticas, reprocesse os arquivos e limpe o cache relevante da página/CDN.
- Use lazy nas galerias e eager/high apenas na imagem principal. sizes descreve o layout, não cria dimensões.