code to take a selection of meta fields from a Cpt and present them in a pdf

Home » Snippets » code to take a selection of meta fields from a Cpt and present them in a pdf
0

Created with:

Visibility: 

public

Creator: Adam

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
/**
 * Generate a PDF from a custom post type's metadata.
 *
 * @param int $post_id The ID of the post to generate the PDF for.
 * @param array $meta_keys The meta keys to include in the PDF.
 *
 * @return void
 */
function wpturbo_generate_pdf( $post_id, $meta_keys ) {
    // Load the mPDF library.
    require_once( 'mpdf/autoload.php' );

    // Get the post object.
    $post = get_post( $post_id );

    // Get the metadata for the post.
    $metadata = get_post_meta( $post_id );

    // Filter the metadata to only include the specified keys.
    $metadata = array_filter( $metadata, function( $key ) use ( $meta_keys ) {
        return in_array( $key, $meta_keys );
    }, ARRAY_FILTER_USE_KEY );

    // Create an HTML table from the metadata.
    $html = '<table>';

    foreach ( $metadata as $key => $values ) {
        $html .= '<tr><th>' . esc_html( $key ) . '</th><td>' . esc_html( implode( ', ', $values ) ) . '</td></tr>';
    }

    $html .= '</table>';

    // Generate the PDF.
    $mpdf = new MpdfMpdf();
    $mpdf->WriteHTML( $html );
    $mpdf->Output();
}
				

To use this function, you'll need to call it passing in the ID of the post you want to generate the PDF for, as well as an array of the meta keys you want to include in the PDF. The function will then load the mPDF library, fetch the metadata for the post, filter the metadata to only include the specified keys, and generate an HTML table with the metadata. Finally, it will generate the PDF using the mPDF library and output it to the browser.

Note that this code is just a starting point, and may need to be adapted to suit your specific use case.

Register an account to save your snippets or go Pro to get more features.