我正在为我的woocommerce商店使用礼品卡插件,我想添加一个生成的pdf文件,以允许客户下载pdf格式的礼品卡。
其思想是使用TCpdf或Fpdf生成pdf并将其输出为字符串。
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
echo $pdf->Output(\'S\');
问题是要将此文件作为wp\\U mail的附件获取。现在,我从插件中获得了以下代码,我不知道如何调用pdf:
/**
* Hooks before the email is sent
*
* @since 2.1
*/
do_action( \'kodiak_email_send_before\', $this );
$subject = $this->parse_tags( $subject );
$message = $this->parse_tags( $message );
$message = $this->build_email( $message );
$attachments = ??;
$sent = wp_mail( $to, $subject, $message, $this->get_headers(), $attachments );
$log_errors = apply_filters( \'kodiak_log_email_errors\', true, $to, $subject, $message );
if( ! $sent && true === $log_errors ) {
if ( is_array( $to ) ) {
$to = implode( \',\', $to );
}
$log_message = sprintf(
__( "Email from Gift Cards failed to send.\\nSend time: %s\\nTo: %s\\nSubject: %s\\n\\n", \'kodiak-giftcards\' ),
date_i18n( \'F j Y H:i:s\', current_time( \'timestamp\' ) ),
$to,
$subject
);
}
有人能帮我吗?
谢谢你的回答!
SO网友:Shaun Cockerill
可以使用标准的“wp\\U mail”功能添加附件,但是您需要连接到phpmailer_init
为此采取的行动。
因为这将需要在没有任何上下文的情况下调用另一个函数,所以可能需要在use ( $attachments )
语句,将附件内容存储为全局变量或属性,或将附件生成代码放入新函数中。
我可以看到OP的代码似乎是在类方法的上下文中,所以我将尝试创建一个兼容/一致的示例。
// Previous Code...
// Use this action to generate and/or attach files.
add_filter( \'phpmailer_init\', array( $this, \'add_attachments\' ) );
// And/or store the attachments as a property.
$this->set_attachments( $attachments );
$sent = wp_mail( $to, $subject, $message, $this->get_headers() );
// Log errors etc...
if ( ! $sent ) {
//...
$this->log_error( $error_message );
}
}
/**
* Add attachments to the email.
*
* This method must be public in order to work as an action.
* @param PHPMailer\\PHPMailer\\PHPMailer $phpmailer
*/
public function add_attachments( $phpmailer ) {
// Remove filter to prevent attaching the files to subsequent emails.
remove_action( \'phpmailer_init\', array( $this, \'add_attachments\' ) );
// Get or generate the attachments somehow.
foreach ( $this->get_attachments() as $filename, $file_contents ) {
try {
$phpmailer->addStringAttachment( $file_contents, $filename );
} catch( \\Exception $ex ) {
// An exception may thrown which would prevent the remaining files from being attached, so we\'ll catch these and log the errors.
// This email may be sent without attachments. Do not try/catch if you don\'t want the email to be sent without all the attachments.
$this->log_error( $ex->getMessage() );
}
}
}
/**
* Abstraction for the logging code to make it reusable.
* @param string $log_message
*/
protected function log_error( $log_message ) {
if ( ! $this->log_errors ) {
return;
}
// Log errors here.
}