Wordpress: displaying an error message - hook admin_notices fails on wp_insert_post_data or publish_post

前端 未结 3 421
长发绾君心
长发绾君心 2021-01-18 09:11

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

This should be easy hooking wp_insert_post_data

相关标签:
3条回答
  • 2021-01-18 09:47

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

    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.

    0 讨论(0)
  • 2021-01-18 09:47
    if($out = $_SESSION['admin_notices']) { 
          $_SESSION["admin_notices"] = ""; 
          echo $out; 
    }
    

    This condition is always TRUE so it always reset your $_SESSION['admin_notices'] var

    0 讨论(0)
  • 2021-01-18 09:56

    You can simply do like WordPress do : using transients like this :

    function set_post_pending($data, $postarr) {
        // If it's not valid...
            $error = "You are missing some Custom Fields.";
            set_transient( get_current_user_id().'missingfield', $error );
            $data['post_status'] = 'pending';
        return $data;
    }
    add_filter('wp_insert_post_data', 'set_post_pending',1,2);
    
    function show_admin_notice() {
        if($out = get_transient( get_current_user_id().'missingfield' ) ) {
            delete_transient( get_current_user_id().'missingfield' );
            echo "<div class=\"error\"><p>$out</p></div>";
        }
        // return false; // nothing to return here
    }
    add_action('admin_notices', "session_admin_notice");
    

    ps : avoid $_SESSION in WordPress, thx

    0 讨论(0)
提交回复
热议问题