Dynamically attaching PDF files to your emails

Described filter is available in ShopMagic since version 2.34.0. Make sure, you've updated your plugin

Basically, you can attach only a specific PDF file to an email - each of your Customer will recieve the same file in an attachment. This is fine, when you want to email some ebook or similar content, but things get complicated when you'd like to send a personalized file (e.g. a ticket) to each person. Now, this can be possible through WordPress filter for the list of attached files.

Adding custom PDF files

Hooking into shopmagic/core/action/send_mail/attachments_paths enables you to filter the files you attach in an email.

Callback function contains data of:

  • absolute paths of currently listed attachments. It is a good idea to sanitize paths before returning the filter, but our plugin additionally checks if referenced file exists on the server.
  • fields submitted in the action form on the admin side. To access data from action settings you should use $action_fields in ContainerInterface.
  • data hydrated to the action, while processing (e.g. Customer, Order, etc.). Data is stored in an array of objects. You can reference the object mostly by the shared interface.

The paths you specify must reference the absolute path to file on the server.

Code example

add_filter('shopmagic/core/action/send_mail/attachments_paths', 'attach_dynamic_files', 10, 3);

 * If a registered customer triggers an automation we specify, get Customer's ID and attach a file named **ticket-$customer_id**.
 * The file must be already on server.
function attach_dynamic_files( array $attachments, \Psr\Container\ContainerInterface $action_fields, array $provided_data ) {
  // If this is not the action, we want to add dynamic files, return original value.
  if ( ! $action_fields->has('subject_value') || $action_fields->get('subject_value') !== 'Grab your ticket') {
    return $attachments;

  // Check if Customer is available.
  if ( ! isset( $provided_data[\WPDesk\ShopMagic\Customer\Customer::class] ) ) {
    return $attachments;

  $customer = $provided_data[\WPDesk\ShopMagic\Customer\Customer::class];

  if ( ! $customer->is_guest() ) {
    $file_path = '/absolute/path/to/file/on/server/ticket-' . $customer->get_id() . '.pdf';
    // Must return as an array - there may be multiple attachments.
    return [ $file_path ];

  return $attachments;
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.

Still need help? Contact Us Contact Us