'WordPress makes an auto-draft as soon as I enter the page
What is the problem
I am creating a system for a client and whenever I enter my plugin editor page, WordPress automatically creates an auto-draft for that post, there is no time interval as it usually has. After it creates one auto-draft, it awaits correctly for the time interval to end before creating the next one. It only happens with my plugin.
Why I want to fix it
Just like what happened to me, users may be annoyed by the huge amount of auto-drafts being created. A lot of browsers, such as Microsoft Edge, Chrome, and Opera, have the "Auto Refresh" feature, every time the editor page is unused for a long time, it needs to be refreshed to be accessed again. Every time the page is reloaded, WordPress (my plugin) insists on creating an auto-draft instantly.
My code
<?php
// File: TDMPostEditor.class.php
class TDPMPostEditor {
public object $post;
private array $default_settings;
public function __construct(array $settings) {
$this->default_settings = $settings;
}
public function setPost(int $post_ID) : void {
$this->post = new stdClass();
foreach (get_post($post_ID) as $key => $value) {
$this->post->{$key} = $value;
}
foreach ($this->default_settings as $key => $default_value) {
$this->post->{$key} = (bool)$this->getPostMeta($key) ? $this->getPostMeta($key) : $default_value;
}
}
public function getPostMeta(string $key, string $single = "single") : mixed {
return get_post_meta($this->post->ID, $key, $single == "single" );
}
public function savePost() : void {
$post_ID = (string)$this->post->ID;
$fields = $this->default_settings;
foreach ( $fields as $key => $default ) {
$key_exists = array_key_exists($key, $_POST);
$value = "";
switch ( gettype($default) ) {
case "integer":
$value = !$key_exists ? $default : $_POST[ $key ];
break;
case "string":
$value = !$key_exists ? $default : $_POST[ $key ];
break;
case "boolean":
$value = !$key_exists ? "0" : "1";
break;
case "array":
$value = !$key_exists ? wp_json_encode($default) : wp_slash($_POST[ $key ]);
break;
default:
break;
}
update_post_meta($post_ID, $key, $value);
}
}
public function render() : void { ... }
}
I assumed that since the post did not exist yet, every time I run get_post($post_ID), it checks it does not exist and creates a draft before returning me the post. So, I tried this:
public function setPost(int $post_ID) : void {
$this->post = new stdClass();
if (get_post_status( $post_ID ) !== false) {
foreach (get_post($post_ID) as $key => $value) {
$this->post->{$key} = $value;
}
}
foreach ($this->default_settings as $key => $default_value) {
$this->post->{$key} = (bool)$this->getPostMeta($key) ? $this->getPostMeta($key) : $default_value;
}
}
Still, no success.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
