Created
March 27, 2017 06:15
-
-
Save maheshwaghmare/bfd599f4270e9331b95e1d3da9e8721b to your computer and use it in GitHub Desktop.
WordPress Generate Downloadable File
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Add below code in themes functions.php OR you can add this in your plugin too. | |
| * | |
| * Here, | |
| * | |
| * - We generate the `.json` file. | |
| * - We can change the file type as per requirement. | |
| */ | |
| /** | |
| * Step 1: Add Download Button | |
| */ | |
| add_action( 'wp_head', 'my_prefix_download_button' ); | |
| function my_prefix_download_button() { | |
| ?> | |
| <a href="<?php echo esc_url( admin_url( 'admin-ajax.php?action=my_prefix_download_file' ) ); ?>" class="button button-primary" ><i class="dashicons dashicons-download"></i> <?php _e( 'Download', 'astra-theme' ); ?></a> | |
| <?php | |
| } | |
| /** | |
| * Step 2: Register AJAX | |
| * | |
| * Here, We generate the `.json` file. | |
| * | |
| * For other file types | |
| */ | |
| add_action( 'wp_ajax_my_prefix_download_file', 'my_prefix_download_file' ); | |
| add_action( 'wp_ajax_nopriv_my_prefix_download_file', 'my_prefix_download_file' ); | |
| function my_prefix_download_file() { | |
| // File name. | |
| $file_name = 'my-file-' . date( 'd-m-Y' ); | |
| // File contents. | |
| $my_array = array( | |
| 'one' => __( 'One', 'my-textdomain' ), | |
| 'two' => __( 'Two', 'my-textdomain' ), | |
| 'three' => __( 'Three', 'my-textdomain' ), | |
| ); | |
| $file_contents = json_encode( $my_array ); | |
| // Generate downloadable file. | |
| header( 'Content-Description: File Transfer' ); | |
| header( 'Content-type: text/json' ); | |
| header( 'Content-Disposition: attachment; filename="'.$file_name.'.json"' ); | |
| header( 'Content-Transfer-Encoding: binary' ); | |
| header( 'Expires: 0' ); | |
| header( 'Cache-Control: must-revalidate' ); | |
| header( 'Pragma: public' ); | |
| echo $file_contents; | |
| exit; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment