WordPress的钩子,将实例化一个类可以使用get_post_types publish_CPT前勾
问题描述:
我有,我需要实例化一个类WordPress的,这样在构造函数中,我可以使用的功能get_post_types,并有前弯钩发生的问题publish_post钩子(我假设是在publish_CPT钩子周围)。WordPress的钩子,将实例化一个类可以使用get_post_types publish_CPT前勾
这里是我到目前为止的代码
class Transient_Delete {
/**
* @var array of all the different post types on the site
*/
private $postTypes;
/**
* @var array of wordpress hooks we will have to assemble to delete all possible transients
*/
private $wpHooks;
public static function init() {
$class = __CLASS__;
new $class;
}
public function __construct()
{
$this->postTypes = array_values(get_post_types(array(), 'names', 'and'));
$this->wpHooks = $this->setWpHooks($this->postTypes);
add_action('publish_alert', array($this, 'deleteAlertTest'));
}
private function setWpHooks($postTypes)
{
$hooks = array_map(function($postType) {
return 'publish_' . $postType;
}, $postTypes);
return $hooks;
}
private function deleteAlertTest($post)
{
$postId = $post->ID;
echo 'test';
}
}
add_action('wp_loaded', array('Transient_Delete', 'init'));
这里的另一个值得注意的是,这是在MU-plugins目录。
注:“通知”的publish_alert是一个自定义后的类型。
答
确定这是我的错,它看起来像如果我改变deleteAlertTest功能的公共publish_alert正常工作挂钩。任何想法为什么它是一个私人函数有这种效果?它在同一个班级内。
当您挂钩一个动作时,传递给它的函数将被直接调用,而不需要任何引用。如果函数是类中的私有函数,则不能通过执行动作来识别。您需要使用对象引用来调用deleteAlertTest。或者,您可以挂钩可用的pubilc函数,然后通过该函数内的对象引用调用此私有函数。 – Junaid