Here is an example of adding new magic tags to PDF Ink for on-the-fly and totally-customized watermarks.
A Brazilian customer using WooCommerce requested a magic tag to display the Cadastro de Pessoas Físicas (CPF) on PDFs. CPF is a taxpayer identification number all citizens of Brazil must use to shop online within Brasil. In order to collect CPF data from customers, our customer uses the Woocommerce Extra Checkout Fields for Brazil plugin.*
We wrote the following code to creat the magic tag [BILLING_CPF] to import any customer’s CPF number into their personalized PDF. The plugin mentioned above must be in use, or this code will need to be modified to the plugin that *is* being used for CPF.
function custom_checkout_field_magic_tag( $content, $key, $order_id, $product_id ) {
// First we need to get the WooCommerce order object from the order id
// you can get a lot of info from the order object ( $order in this case)
$order = wc_get_order( $order_id );
if ( ! $order instanceof WC_Order ) {
error_log( 'No WC_Order object.' );
return $content;
}
// The CPF plugin stores CPFs in WooCommerce order meta, making it easy to fetch
// you might want to do testing to make sure the following line, if altered
// actually fetches what *you* need from the database:
// Other things which could be fetched: https://stackoverflow.com/a/44708344
$billing_cpf = $order->get_meta( '_billing_cpf' );
// If there isn't a CPF, we give up
if ( ! $billing_cpf || $billing_cpf === '' ) {
error_log( 'No Billing CPF found for this order.' );
return $content;
}
// remove . - / from CPF, keep it numbers only
$billing_cpf = str_replace( [ '.', '-', '/' ], '', $billing_cpf );
// When we find [BILLING_CPF] in a watermark, replace it with the order CPF
if ( ! empty( $billing_cpf ) ) {
$content = preg_replace( '/[BILLING_CPF]/', $billing_cpf, $content );
} else {
error_log( 'Billing CPF became an empty string or 0 after .-/ characters were removed.' );
}
return $content;
}
add_filter( 'pdfink_filter_placement_content', 'custom_checkout_field_magic_tag', 10, 4 );
This is simple PHP code. It can be edited ad lib to accomplish your particular goals. Add the code to a (child) theme functions.php file manually or using the Code Snippets plugin. Here’s a nice list of all the order details you can fetch using the WooCommerce order object.
Set up a private dummy product (price: 0.00) and live test with a purchase to confirm the magic tag function. Alternatively, this magic tag will work with the Test Lab feature — but only if you include a valid WooCommerce order number in the Magic Tags backend settings.
Check out more examples using the ‘pdfink_filter_placement_content‘ hook.
*(This CPF plugin probably does what it says, and this link is not an endorsement.)