You can try to do it in two ways.
The first one, much more simple, is to save a temporary PDF file somewhere, for example in a uploads
directory, use it as attachment and delete if after the call to wp_mail()
function is made:
function my_custom_save_post( $post_id, $post, $update ) {
if( ! $update ) { return; }
if( wp_is_post_revision( $post_id ) ) { return; }
if( defined( 'DOING_AUTOSAVE' ) and DOING_AUTOSAVE ) { return; }
if( $post->post_type != 'MYCUSTOMPOST' ) { return; }
$url = wp_nonce_url( admin_url( "myCustomUrl" ), 'my_nounce_name' );
$contents = file_get_contents( $url );
# here temporary file name is a fixed string
# but it better to be some unique string
# (use current timestamp, post ID, etc)
$tempfile = ABSPATH . 'uploads/filename.pdf';
file_put_contents( $tempfile, $contents );
$attachments = array( $tempfile );
$headers = 'From: My Name <[email protected]>' . "\r\n";
wp_mail( '[email protected]', 'subject', $url, $headers, $attachments );
unlink( $tempfile );
}
add_action( 'save_post', 'my_custom_save_post', 10, 3 );
The second is just a guess and needs to be tested. WordPress rely on PHPMailer
component for sending emails. That component has a addStringAttachment
method which allows to attach a binary object assigned to a PHP variable as a email file attachment. Here is the question about this topic. I don't see any way this could be used via wp_mail()
function but in theory you can try to do it via phpmailer_init
hook:
function my_attach_pdf( $mailer_instance ) {
$url = wp_nonce_url( admin_url( "myCustomUrl" ), 'my_nounce_name' );
$contents = file_get_contents( $url );
$mailer_instance->addStringAttachment( $contents, 'your_file_name.pdf' );
}
function my_custom_save_post( $post_id, $post, $update ) {
if( ! $update ) { return; }
if( wp_is_post_revision( $post_id ) ) { return; }
if( defined( 'DOING_AUTOSAVE' ) and DOING_AUTOSAVE ) { return; }
if( $post->post_type != 'MYCUSTOMPOST' ) { return; }
$headers = 'From: My Name <[email protected]>' . "\r\n";
add_action( 'phpmailer_init', 'my_attach_pdf' );
wp_mail( '[email protected]', 'subject', $url, $headers, $attachments );
remove_action( 'phpmailer_init', 'my_attach_pdf' );
}
add_action( 'save_post', 'my_custom_save_post', 10, 3 );
I'm really curious if the second approach would work. Maybe give it a test one day. If you test it, please give some feedback.
$attachments
array item value, not the URL.$url = wp_nonce_url( admin_url( "myCustomUrl" ), 'my_nounce_name' );
line should do and what is your"myCustomUrl"
does mean. Where are your PDF file located?