WordPress:显示错误消息-在wp_insert_post_data或publish_post上挂钩admin_notices失败 [英] Wordpress: displaying an error message - hook admin_notices fails on wp_insert_post_data or publish_post

查看:231
本文介绍了WordPress:显示错误消息-在wp_insert_post_data或publish_post上挂钩admin_notices失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要添加验证,因此,如果某个帖子属于特定类别,则需要设置某些自定义字段".

I'm adding validation so if a post is in a particular category, it needs certain Custom Fields to be set.

这应该很容易挂钩wp_insert_post_dataadmin_notices,但是有一个重定向导致admin_notices回调消失.

This should be easy hooking wp_insert_post_data and admin_notices, but there is a redirect that causes the admin_notices callback to disappear.

确定-因此,我创建了一个使用会话在重定向中存储我的错误消息的黑客:

OK - So I created a hack that uses the Session to store my error message across the redirect:

function set_post_pending($data, $postarr) {
    // If it's not valid...
        $error = "You are missing some Custom Fields.";
        $_SESSION['admin_notices'] = $error;
        $data['post_status'] = 'pending';
    return $data;
}
add_filter('wp_insert_post_data', 'set_post_pending',1,2);

function session_admin_notice() {
    if($out = $_SESSION['admin_notices']) {
        $_SESSION["admin_notices"] = "";
        echo $out;
    }
    return false;
}
add_action('admin_notices', "session_admin_notice");

此解决方案的问题是一些为何在调用session_admin_notice时会话不可用,这有一个简单(但 crazy )解决方案:

The problem with this solution is that somehow the session is not available when calling session_admin_notice, which has an easy (but crazy) solution:

public static function fix_session_bs() {
    // TODO: Why do I have to do this?
    if(!session_id() && $_COOKIE["PHPSESSID"]) {
        session_start($_COOKIE["PHPSESSID"]);
    }
}
add_action('admin_init', 'fix_session_bs');

问题是:为什么我必须经历所有这些疯狂的事情才能抛出错误消息?

The question is: Why do I have to go through all this craziness to throw an error message?

我在做什么错了?

推荐答案

Wordpress不使用会话,并且如果register_globals处于打开状态,它将清除$_SESSION数组.

Wordpress doesn't use sessions, and if register_globals is on it will clear the $_SESSION array.

Wordpress使用URL中的message整数传递消息,然后在wp-admin文件夹中的相关edit-[type]-form.php文件中定义消息数组.我认为您可能可以将自己的变量附加到重定向中,然后在admin_notices挂钩函数中获取它.查看edit-[type]-form.php文件以了解其工作方式.

Wordpress passes it's messages along using a message integer in the URL, an array of messages is then defined in the relevant edit-[type]-form.php file in the wp-admin folder. I think you could probably append your own variable to the redirect and then get that in your admin_notices hook function. Take a look at the edit-[type]-form.php files to get an idea of how this might work.

这篇关于WordPress:显示错误消息-在wp_insert_post_data或publish_post上挂钩admin_notices失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆