skip to Main Content

I have added the code below to my WooCommerce site to display the file format of a downloadable asset.

to be displayed on a single product page

For ZIP files, I would like the display to indicate the files which are contained within the compressed archive, so the shoppers of simple/downloadable products know the formats of the product data which they will receive. How can this be achieved please?

image

global $product;
$downloads = $product->get_files();
foreach( $downloads as $key => $each_download ) {
  $info     = pathinfo($each_download["file"]);
  $ext      = $info['extension'];
  $formats .= $ext . ", ";
}
echo '<p> File Format: '. $formats .'</p>';
?>```

2

Answers


  1. You can use the ZipArchive to gather the index of the files within the zip.

    Ensure that you have the module installed as detailed here https://www.php.net/manual/en/zip.installation.php

    public function buildZipBreakdown(string $zipFile): array
    {
        $result = [];
        if (file_exists($zipFile)) {
            $result = pathinfo($zipFile);
            if ($result['extension'] == "zip") {
                $za = new ZipArchive();
                $za->open($zipFile);
                $result['num_files']  = $za->numFiles;
                if ($za->numFiles>0) {
                    $result['files'] = [];
                    for ($i=0; $i<$za->numFiles; $i++) {
                        $file_object = $za->statIndex($i);
                        $result['files'][] = [
                            "filename" => $file_object['name'],
                            "size" => $file_object['size'],
                            "date" => date('Y-m-d H:i:s', $file_object['mtime'])
                        ];
                    }
                } else {
                    throw new Exception("EMPTY_INVALID_ZIP");
                }
            } else {
                throw new Exception("NOT_ZIP_EXT");
            }
        } else {
            throw new Exception("NOT_FOUND");
        }
        return  $result;
    }
    

    You can tailor it to your needs.

    Login or Signup to reply.
  2. Hello like @user6316291 said, zipArchive works.
    Since it’s in WooCommerce, you can try this code.

    <?php
    /*
     * This block should be in the proper place of mytheme/woocommerce/templates/single-product/meta.php file.
     * Hope this helps you, but still, enjoy at your own risk. :)
     */
    
    /**
     * Single Product Meta
     *
     * This template can be overridden by copying it to yourtheme/woocommerce/single-product/meta.php.
     *
     * HOWEVER, on occasion WooCommerce will need to update template files and you
     * (the theme developer) will need to copy the new files to your theme to
     * maintain compatibility. We try to do this as little as possible, but it does
     * happen. When this occurs the version of the template file will be bumped and
     * the readme will list any important changes.
     *
     * @see         https://docs.woocommerce.com/document/template-structure/
     * @package     WooCommerceTemplates
     * @version     3.0.0
     */
    if ( ! defined( 'ABSPATH' ) ) {
        exit;
    }
    global $product;
    ?>
    <div class="product_meta">
        <?php do_action( 'woocommerce_product_meta_start' ); ?>
        <?php if ( wc_product_sku_enabled() && ( $product->get_sku() || $product->is_type( 'variable' ) ) ) : ?>
            <span class="sku_wrapper"><?php esc_html_e( 'SKU:', 'woocommerce' ); ?> <span class="sku"><?php echo ( $sku = $product->get_sku() ) ? $sku : esc_html__( 'N/A', 'woocommerce' ); ?></span></span>
        <?php endif; ?>
        <?php echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>
        <?php echo wc_get_product_tag_list( $product->get_id(), ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', count( $product->get_tag_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>
    
    
        <?php do_action( 'woocommerce_product_meta_end' ); ?>
    
    <?php
    // ########################################
    
    /**
     * Display files in zip file.
     *
     * @author Precious Omonzejele (CodeXplorer)
     * @param string $zip_full_path The absolute url path.
     * @param string $display (optional) any valid key of pathinfo(), default is extension.
     * @param bool   $avoid_duplicate (optional) set true if you don't want duplicate list, default is false.
     * @return mixed false if zip file couldn't be opened, string otherwise
     */
    function pekky_break_down_zip( $zip_full_path, $display, $avoid_duplicate = false ) {
        // Divide file path.
        $path = explode( '/uploads/', $zip_full_path );
        if ( empty( $path ) ) {
            return false;
        }
    
        $file_path = WP_CONTENT_DIR . '/uploads/' . $path[1];
    
        $zip = new ZipArchive();
    
        $res  = $zip->open( $file_path );
        $data = '';
        // To detect if a file has been listed, to avoid repetition.
        $data_store = array();
        if ( true === $res ) {
            for ( $i = 0; $i < $zip->numFiles; $i++ ) {
    
                $info        = pathinfo( $zip->getNameIndex( $i ) );
                $single_info = $info[ $display ];
    
                // Does something exist and if avoid_duplicate is set, is it already listed?
                if ( $single_info ) {
                    if ( $avoid_duplicate && in_array( $single_info, $data_store, true ) ) {
                        continue;
                    }
                    $data_store[] = $single_info;
                    $data        .= $single_info . ( ( $zip->numFiles - $i ) == 1 ? '' : ', ' );
                }
            }
            $zip->close(); // Always close this 👽.
            return $data;
        } else {
            return false;
        }
    }
        // End of Custom Function.
    
        $downloads   = $product->get_downloads();
        $part_needed = 'extension';
        $formats     = '';
    foreach ( $downloads as $key => $each_download ) {
        $file_path = $each_download['file'];
        $info      = pathinfo( $file_path );
        $f_data    = $info[ $part_needed ];
    
        echo '<br><br>';
        // Is it a zip file?
        if ( 'zip' === $f_data ) {
            $_format  = pekky_break_down_zip( $file_path, $part_needed, false );
            $formats .= ( ! empty( $_format ) ? $_format : '' );
        } else {
            $formats .= ( ! empty( $f_data ) ? $f_data . ', ' : '' );
        }
    }
    // Translators: %s is the format data.
    $format_text = sprintf( __( 'file Format: %s', 'woocommerce' ), $formats );
    echo ( ! empty( $formats ) ? '<p>' . esc_attr( $format_text ) . '</p>' : '' );
    ?>
    </div>
    

    you can find the gist here: https://gist.github.com/Preciousomonze/88e30062982a20b2f9af98e834964969

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search