repeater = 'team_attendants'; // Name of the repeater field that are to be downloadable. // @TODO add the post type that the download button should be displayed at. $this->post_types = 'hold'; // The post type that the download metabox is to be displayed at. $this->init(); } public function init() { // Register meta box. add_action( 'add_meta_boxes', array( $this, 'register_meta_boxes' ) ); // Add a new custom endpoint for the download rule. add_action( 'init', array( $this, 'add_rewrite_rule' ) ); add_filter( 'query_vars', array( $this, 'add_query_vars' ) ); // Generate the file. add_action( 'parse_request', array( $this, 'parse_request' ) ); } /** * Handle the custom endpoint we added. */ public function parse_request( $wp ) { // If the key does not exist, stop execution. if ( ! array_key_exists( 'cs-repeater-page-id', $wp->query_vars ) ) { return; } $page = absint( $wp->query_vars['cs-repeater-page-id'] ); $output = ''; if( have_rows( $this->repeater, $page ) ) { $rows = get_field( $this->repeater, $page ); $field_count = count( $rows[0] ); foreach ( $rows as $fields ) { $count = 1; foreach ( $fields as $value ) { $output .= $value; $count++; if ( $count < $field_count ) { $output .= ','; } } $output .= "\n"; } } // Send the downloadable file. header("Content-type: text/plain"); header("Content-Disposition: attachment; filename=attendants.txt"); // Print the content. print $output; exit(); } /** * Add the needed query args. */ public function add_query_vars( $query_vars ) { $query_vars[] = 'cs-repeater-page-id'; return $query_vars; } /** * Adds a rewrite rule for our downloadable file. */ public function add_rewrite_rule() { add_rewrite_rule( '^cs-repeater-download/([0-9]+)/?', 'index.php?cs-repeater-page-id=$matches[1]', 'top' ); } /** * Register meta box(es). */ public function register_meta_boxes() { add_meta_box( 'meta-box-id', __( 'Download teams', 'cs-repeater-download' ), array( $this, 'meta_box_callback' ), $this->post_types, 'side' ); } /** * Meta box display callback. * * @param \WP_Post $post Current post object. */ public function meta_box_callback( $post ) { ?>