Skip to content

Instantly share code, notes, and snippets.

@luisabarca
Last active July 25, 2019 03:01
Show Gist options
  • Save luisabarca/3cf7a8160b9c1c3ad07942f2798a293a to your computer and use it in GitHub Desktop.
Save luisabarca/3cf7a8160b9c1c3ad07942f2798a293a to your computer and use it in GitHub Desktop.
Create a PDF file from a plugin.
<?php
add_action( 'save_post', 'bp_generate_pdf', 10, 2 );
public function bp_generate_pdf( $post_id, $post ) {
// check autosave and permissions.
$should_generate_pdf = $_POST['generatepdf'] ?? 0;
if ( $should_generate_pdf ) {
$prev_attach_id = get_post_meta( $post_id, 'pdf_attachment_id', true );
if ( $prev_attach_id > 0 ) {
bp_delete_attachments( $post_id );
}
// Generate PDF file and returns the attachment ID.
$attach_id = generate_pdf( $post_id );
// PDF URL.
$src = wp_get_attachment_url( $attach_id );
update_post_meta($post_id, 'pdf_attachment_id', $attach_id);
update_post_meta($post_id, 'pdf_src', $src);
}
}
function generate_pdf( $post_id ) {
// This is the name of your pdf template.
$source_file = 'PDF-Form';
$filename = sprintf( '%s-%d.pdf', $source_file, $post_id );
// Data.
$form_data = [];
$data = get_post_meta( $post_id );
// Convert metadata to a simple array.
foreach ( $data as $key => $value ) {
$form_data[ $key ] = $value[0];
}
// Please define your PLUGIN_PATH and make sure the pdf file exists.
$pdf_data = array(
'filename' => $filename,
'template_path' => PLUGIN_PATH . 'public/assets/' . $source_file . '.pdf',
'output_path' => PLUGIN_PATH . $filename
);
BP_PDF::create_document( $pdf_data, $form_data );
return BP_PDF::attach_to_object( $post_id, $pdf_data );
}
function bp_delete_attachments( $post_id ) {
// Attachments.
$attachments = get_children([
'post_parent' => $post_id,
'post_type' => 'any',
'post_per_page' => -1,
'post_status' => 'any'
]);
// Validate.
if ( is_array( $attachments ) && sizeof( $attachments ) > 0 ) {
// Delete attachments.
foreach ( $attachments as $item ) {
wp_delete_attachment( $item->ID, true );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment