【问题标题】:Can I execute a php file from my functions.php in wordpress?我可以在 wordpress 中从我的 functions.php 执行一个 php 文件吗?
【发布时间】:2013-08-26 14:38:04
【问题描述】:

我正在使用一个函数来执行一个发送带有附件的电子邮件的代码。 此函数与来自 woocommerce 的过滤器挂钩。

我想重建这个函数来执行来自外部 php 文件的代码。 这在 Wordpress 中可行吗?

我想从外部脚本执行它的原因是因为我想要更多的功能,电子邮件的发件人和附件是从会话中生成的。

在我的子主题的function.php-

function send_invoice () 
{
    $attachments = array( WP_CONTENT_DIR . '/themes/mytheme/invoices/invoice.pdf' );
    wp_mail( 'targetmail@domain.com', 'Attachment test', 'The message', 'header', $attachments);
}
add_filter( 'woocommerce_email_attachments', 'send_invoice' );

有没有办法从我的functions.php中执行一个php文件?

进一步阐述: 我正在尝试将以前的脚本转换为: 函数.php

function execute_send_invoice () {
    send_invoice();
}   
add_filter( 'woocommerce_email_attachments', 'execute_send_invoice' );

然后是 send_invoice() 的代码;我的functions.php之外的某个地方,例如,位于我的模板目录中的myscript.php中。

【问题讨论】:

  • 如果包含文件,无论是否包含wordpress,都可以正常调用函数
  • 所以我不必链接新的php文件,如果我只是在那里编写我的函数,我可以在我的functions.php中调用它吗?顺便说一句,您能定义“包含”吗?我必须手动链接它,还是在我的主题目录中包含一个文件?
  • 查看我的答案以获得解释。使用 wordpress,当主题处于活动状态时,functions.php 会自动包含在内。

标签: php wordpress woocommerce


【解决方案1】:

不用说,在 PHP 中运行外部脚本时应该非常小心。

如果在执行您的 PHP 文件之前没有由 wordpress 完成某种准备工作,则运行外部代码有两种主要方法。使用第一个,您必须进一步将PHP包含在<?php ?>标签中,但这是我个人的建议。

include('full_or_relative_php_path_to_file.php');

eval(file_get_contents('full_or_relative_php_path_to_file.php'));

【讨论】:

  • 我在这里遇到了同样的问题,您包含了哪个文件以及如何包含。
【解决方案2】:

如果functions.php 文件位于当前活动的主题内,则默认包含该文件。因此,您可以像往常一样访问和调用该函数(就好像它是在您将要调用该函数的同一页面上定义的一样)。

see here

【讨论】:

  • 这是我试图实现的功能,只是倒退。我的目标是拥有这样的功能: function execute_send_invoice() { send_invoice(); } add_filter('woocommerce_email_attachments', 'execute_send_invoice');并拥有 send_invoice() 的代码;在我的functions.php文件之外。
  • 在这种情况下,在functions.php中使用includerequire来添加包含send_invoice()的PHP文件。
猜你喜欢
  • 2014-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2020-11-19
  • 2021-11-23
相关资源
最近更新 更多