Skip to content

Instantly share code, notes, and snippets.

@dkjensen
Created March 5, 2021 21:16
Show Gist options
  • Save dkjensen/f7b6500322df06c5f53a0c2161d2bddf to your computer and use it in GitHub Desktop.
Save dkjensen/f7b6500322df06c5f53a0c2161d2bddf to your computer and use it in GitHub Desktop.
<?php
add_action( 'template_redirect', function() {
if ( isset( $_POST['_action'] ) && $_POST['_action'] === 'wc_cart_pdf_share' ) {
if ( ! wp_verify_nonce( $_POST['_wpnonce'] ?? '', 'wc_cart_pdf_share' ) ) {
wp_die( esc_html__( 'Invalid nonce' ) );
}
if ( ! is_email( $_POST['email'] ?? '' ) ) {
wp_die( esc_html__( 'Invalid email' ) );
}
if ( ! class_exists( '\\Mpdf\\Mpdf' ) ) {
wp_die( esc_html__( 'WC Cart PDF not installed' ) );
}
$mpdf = new \Mpdf\Mpdf(
array(
'mode' => get_locale(),
'format' => 'A4',
'default_font' => 'dejavusans',
)
);
$mpdf->shrink_tables_to_fit = 1;
$mpdf->simpleTables = true;
$mpdf->packTableData = true;
$mpdf->autoLangToFont = true;
$content = $css = '';
$cart_table = wc_locate_template( 'cart-table.php', '/woocommerce/wc-cart-pdf/', WC_CART_PDF_PATH . '/templates/' );
$css = wc_locate_template( 'pdf-styles.php', '/woocommerce/wc-cart-pdf/', WC_CART_PDF_PATH . '/templates/' );
do_action( 'wc_cart_pdf_before_process' );
/**
* Run the calculate totals method for plugins that modify the cart using this hook
*/
WC()->cart->calculate_totals();
if ( file_exists( $cart_table ) ) {
ob_start();
include $cart_table;
$content = ob_get_clean();
}
if ( file_exists( $css ) ) {
ob_start();
include $css;
$css = apply_filters( 'woocommerce_email_styles', ob_get_clean() );
}
if ( is_rtl() ) {
$mpdf->SetDirectionality( 'rtl' );
}
/**
* Hook to modify mPDF object before generating
*
* @since 2.0.6
*/
$mpdf = apply_filters( 'wc_cart_pdf_mpdf', $mpdf );
$mpdf->WriteHTML( $css, \Mpdf\HTMLParserMode::HEADER_CSS );
$mpdf->WriteHTML( $content, \Mpdf\HTMLParserMode::HTML_BODY );
$file_path = get_temp_dir() . 'WC_Cart-Share-' . gmdate( 'Ymd' ) . bin2hex( openssl_random_pseudo_bytes( 5 ) ) . '.pdf';
$mpdf->Output( $file_path, 'F' );
$body = esc_html__( 'See attachment' );
$attachments = array( $file_path );
wp_mail( $_POST['email'], esc_html__( 'Email subject' ), $body, array(), $attachments );
unlink( $file_path );
}
} );
add_action( 'woocommerce_proceed_to_checkout', function() {
?>
<form method="post">
<p>
<input type="email" name="email" placeholder="<?php esc_html_e( 'Email address' ); ?>" />
<?php wp_nonce_field( 'wc_cart_pdf_share' ); ?>
<input type="hidden" name="_action" value="wc_cart_pdf_share" />
<input type="submit" value="<?php esc_html_e( 'Send' ); ?>" />
</p>
</form>
<?php
}, 22 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment