WordPress Get Edited Post ID
Working on my plugin Disable Gutenberg, I needed a way to get the ID of an edited post. Not on the front-end, but on the “Edit Post” screen in the WP Admin Area. Unfortunately WordPress does not provide a built-in core function for handling this, so it’s necessary to roll our own solution.
Get Edited Post ID
Here is the magic function:
function shapeSpace_get_edited_post_id() {
$post = isset($_GET['post']) ? $_GET['post'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null;
$pagenow = isset($GLOBALS['pagenow']) ? $GLOBALS['pagenow'] : null;
if (!empty($post) && !empty($action) && $action === 'edit' && !empty($pagenow) && $pagenow === 'post.php') {
return (int) $post;
}
return 0;
}
No changes need to be made, strictly plug-&-play.
Here is an example of usage:
if ($post_id = shapeSpace_get_edited_post_id()) {
// do stuff with $post_id
}
Related example
Here is a sort of related example showing how to tell if the current post is a Post or Page.
function shapeSpace_post_or_page() {
global $pagenow;
$type = null;
if ($pagenow === 'edit.php') {
if (!isset($_GET['post_type'])) {
$type = 'post'; // posts @ edit.php
} elseif (isset($_GET['post_type']) && $_GET['post_type'] === 'page') {
$type = 'page'; // pages @ edit.php?post_type=page
}
} elseif ($pagenow === 'post.php' && isset($_GET['post'])) {
$post_type = get_post_type($_GET['post']);
if ($post_type === 'post') {
$type = 'post'; // post.php?post=1&action=edit
} elseif ($post_type === 'page') {
$type = 'page'; // post.php?post=1&action=edit
}
} elseif ($pagenow === 'post-new.php') {
if (!isset($_GET['post_type'])) {
$type = 'post'; // post-new.php
} elseif (isset($_GET['post_type']) && $_GET['post_type'] === 'page') {
$type = 'page'; // post-new.php?post_type=page
}
}
return $type;
}
That covers (I think) every possible screen for writing/editing WordPress Posts and Pages. The function itself is not so useful in general, but the inner logic demonstrates how to check for the various “views” possible when working with posts.