在运行save_post操作之后,我也尝试使用admin_notices操作,但它不起作用。我做错了什么?
如果我将admin_notices操作移动到构造函数中,它就可以正常工作(当然,它显示在管理中的每个页面都是不需要的)。我假设这一定是钩子的逻辑顺序还是嵌套本身?
代码示例:
if (!class_exists('CPTToPDF')) {
// FPDF library
require_once(plugin_dir_path(__FILE__) . 'fpdf182/fpdf.php');
class CPTToPDF {
private $pdf;
public function __construct() {
add_action('save_post', array($this, 'render_to_pdf'));
}
public function render_to_pdf() {
//die('Render to PDF running...');
$this->pdf = new FPDF();
add_action('admin_notices', array($this, 'admin_notice__success'));
}
public function admin_notice__success() {
//die('Admin notice running...');
echo 'CPTToPDF: Saved post.';
}
public function admin_notice__error() {
echo 'CPTToPDF: Did not save post.';
}
}
}我将初始钩子放入插件的构造函数方法中的save_post中。这很好(如果我取消对die('Render to PDF running...');行的注释,它就会死掉并显示该消息,因此我知道我的回调可以工作)。
但是,第二个操作/钩子在render_to_pdf回调:add_action('admin_notices', array($this, 'admin_notice__success'));中没有正确启动。
即使我取消了对die('Admin notice running...');的注释,当一个帖子被保存并且新页面被重新加载时,我也得不到输出(除了默认的“PageUpdated.ViewPage”管理通知之外)。所以嵌套的操作似乎不起作用,我不知道为什么。
发布于 2020-06-10 19:25:15
您需要通过URL向下一页发送通知消息--或者可能是引用特定标准通知消息的键。
我建议将它封装在它自己的功能中。就像..。
public function render_to_pdf() {
// ... whatever you need to do
my_trigger_notice( 1 ); // 1 here would be a key that refers to a particular message, defined elsewhere (and not shown here)
}然后在functions.php (或admin.php文件)中添加新函数:
function my_trigger_notice( $key = '' ) {
add_filter(
'redirect_post_location',
function ( $location ) use ( $key ) {
$key = sanitize_text_field( $key );
return add_query_arg( array( 'notice_key' => rawurlencode( sanitize_key( $key ) ) ), $location );
}
);
}现在,当页面重定向时,它应该在URL上追加您的通知键,使下一页能够在admin_notice钩子上“捕获”它(也设置在functions.php或admin.php中):
function my_admin_notices() {
if ( ! isset( $_GET['notice_key'] ) ) {
return;
}
$notice_key = wp_unslash( sanitize_text_field( $_GET['notice_key'] ) );
$all_notices = [
1 => 'some notice',
2 => 'some other notice',
];
if ( empty( $all_notices[ $notice_key ] ) ) {
return;
}
?>https://wordpress.stackexchange.com/questions/368697
复制相似问题