• I am having troubles with file encodings while retrieving file names with get_attached_file(). The line:

    get_attached_file( $attachment_id );

    Is getting me results like:

    GAC_14_2_Selo-Casa-Azul_Constru?§?£o-Sustent??vel.pdf

    Where it should be like:

    GAC_14_2_Selo-Casa-Azul_Constru??o-Sustentável.pdf

    The file is correctly stored at the file system; WordPress Media Library also shows correctly; WordPress is at version 4.0.1.

    Why is it not working and what should I do to make it work?

    Below goes all the my code if it helps.
    Its purpose is to regenerate a zip file every time a custom post type post is saved. The zip contains every file attached to the post through Advanced Custom Fields + ACF Repeater.
    The code is working: the zip is generated with the files inside it but the filenames are, as shown above, incorrect.

    function gerar_zip_dos_materiais( $post_id ) {
    // https://stackoverflow.com/questions/23668293/php-dynamically-generated-zip-file-by-ziparchive-cant-be-opened
    $materiais = get_field(‘materiais’);
    $error = ”;
    if ($materiais) {
    if(extension_loaded(‘zip’)){

    $zip = new ZipArchive(); // Carrega a biblioteca zip
    $nome_curto = $slug = basename(get_permalink()); // pega o slug do post
    date_default_timezone_set(‘America/Bahia’);
    $data_agora = date(‘Ymd_His’); // pega a data do post
    $nome_do_zip = $nome_curto . ‘-‘ . $data_agora . ‘.zip’; // Nome do zip
    $path = get_site_url();
    $url_zipao = $path . ‘/wp-content/uploads/materiais/’ . $nome_do_zip;

    if($zip->open($nome_do_zip, ZIPARCHIVE::CREATE)!==TRUE){ // Prepara um zip para carregamento
    $error .= “Falhou ao criar o zip desta vez!”;
    }

    foreach($materiais as $material) {
    $nome_subpasta = $material[‘nome_da_aula’];
    $documentos = $material[‘conteudos_da_aula’];

    foreach ($documentos as $documento) {
    $attachment_id = $documento[‘arquivo_do_conteudo’];
    $url = wp_get_attachment_url( $attachment_id );
    $filename = basename ( get_attached_file( $attachment_id ) );
    $path_absoluto_do_arquivo = get_home_path() . str_replace($path.’/’,”,$url);

    $zip->addFile( $path_absoluto_do_arquivo, ‘Viviane_Rocha/’ . $nome_curto . ‘/’ . $nome_subpasta . ‘/’ . $filename );
    }

    }

    if ($zip->close() === false) {
    exit(“Falou ao fechar o zip desta vez!”);
    }

    if(file_exists($nome_do_zip)) {
    rename($nome_do_zip, ‘../wp-content/uploads/materiais/’.$nome_do_zip);
    }

    $chave = ‘arquivao’;
    $o_zip = $url_zipao;
    if ( !isset($o_zip) || !is_string($o_zip) ) {
    add_post_meta($post_id, $chave, $o_zip, true);
    } else {
    update_post_meta($post_id, $chave, $o_zip);
    }

    } // extension_loaded(‘zip’)
    } // $materiais
    }

    add_action( ‘save_post_materiais’, ‘gerar_zip_dos_materiais’ );

  • The topic ‘Incorrect output with get_attached_file()’ is closed to new replies.