Domanda

Sto utilizzando il seguente codice template per visualizzare i collegamenti di attacco:

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $main_post_id
);

$attachments = get_posts($args);

foreach ($attachments as $attachment)
{
    the_attachment_link($attachment->ID, false);
}

, ma dopo il link che ho bisogno di visualizzare le dimensioni del file. Come posso fare questo?

Sto indovinando avrei potuto stabilire il percorso del file (tramite wp_upload_dir() e un substr() di wp_get_attachment_url()) e call filesize() ma che sembra disordinato, e mi chiedo solo se c'è un metodo integrato in WordPress.

È stato utile?

Soluzione

Per quanto ne so, non ha nulla WordPress integrato per questo, vorrei solo fare:

filesize( get_attached_file( $attachment->ID ) );

Altri suggerimenti

ho usato prima in functions.php per visualizzare la dimensione del file in un formato facilmente leggibile:

function getSize($file){
$bytes = filesize($file);
$s = array('b', 'Kb', 'Mb', 'Gb');
$e = floor(log($bytes)/log(1024));
return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));}

E poi nel mio modello:

echo getSize('insert reference to file here');

vorrei fare:

$attachment_filesize = filesize( get_attached_file( $attachment_id ) );

O con formato leggibile come 423.82 KB

$attachment_filesize = size_format( filesize( get_attached_file( $attachment_id ) ), 2 );

Refs: get_attached_file () , filesize () , size_format ()

Nota: Definisci il tuo $attachment_id

Per trovare la dimensione di un file aggiunto attraverso i campi personalizzati plug-in, ho fatto questo:

$fileObject = get_field( 'file ');
$fileSize   = size_format( filesize( get_attached_file( $fileObject['id'] ) ) );

Basta assicurarsi che si imposta il campo personalizzato "valore di ritorno" a "oggetto file".

C'è una soluzione più facile, per ottenere le dimensioni dei file leggibile.

$attachment_id  = $attachment->ID;
$attachment_meta = wp_prepare_attachment_for_js($attachment_id);

echo $attachment_meta['filesizeHumanReadable'];

che stavo cercando la stessa ed ho trovato questo WordPress built-in soluzione.

$args = array(
    'post_type' => 'attachment',
    'numberposts' => -1,
    'post_status' => null,
    'post_parent' => $main_post_id
);

$attachments = get_posts($args);

foreach ($attachments as $attachment)
{
    $attachment_id = $attachment->ID;
    $image_metadata = wp_get_attachment_metadata( $attachment_id );
    the_attachment_link($attachment->ID, false);
    echo the_attachment_link['width'];
    echo the_attachment_link['height'];
}

wp_get_attachment_metadata()

Per l'audio, almeno, la dimensione del file viene salvato come "metadati".

$metadata = wp_get_attachment_metadata( $attachment_id );
echo $metadata['filesize'];

Questo non possono essere il caso per immagini e video.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top